计算时间差--精确到微秒级

之所以要计算到微秒级,主要是衡量算法的时候,可以有更精确的结果;另外,在我现在的一个应用中,微秒级的计算可以带来更精确的控制。


#include <stdio.h>
#include <sys/time.h>

int main(void)
{
        struct timeval start,end;
        gettimeofday(&start,NULL);
        sleep(3);
        gettimeofday(&end,NULL);
        int timeuse = getTimeSpanUsec(start,end);
        printf("time:%d us\n",timeuse);
        return 0;
}

int getTimeSpanUsec(struct timeval start, struct timeval end)
{
        return (1000000 * (end.tv_sec-start.tv_sec) + end.tv_usec - start.tv_usec);
}
这里包括2个点:

1、struct timeval

struct  timeval{
       long  tv_sec;/*秒*/
       long  tv_usec;/*微妙*/
};

2、gettimeofday

#include<sys/time.h>
int gettimeofday(struct  timeval*tv,struct  timezone *tz ) 


你可能感兴趣的:(c,时间,gettimeofday)