1. 程式人生 > >linux中C語言獲取高精度時鐘gettimeofday函式

linux中C語言獲取高精度時鐘gettimeofday函式

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <sys/time.h>
 5 int    time_substract(struct timeval *result, struct timeval *begin,struct timeval *end)
 6 {
 7     if(begin->tv_sec > end->tv_sec)    return -1;
 8     if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec))    return
-2; 9 result->tv_sec = (end->tv_sec - begin->tv_sec); 10 result->tv_usec = (end->tv_usec - begin->tv_usec); 11 12 if(result->tv_usec < 0) 13 { 14 result->tv_sec--; 15 result->tv_usec += 1000000; 16 } 17 return 0; 18 } 19 int main(int
argc, char **argv) 20 { 21 struct timeval start,stop,diff; 22 memset(&start,0,sizeof(struct timeval)); 23 memset(&stop,0,sizeof(struct timeval)); 24 memset(&diff,0,sizeof(struct timeval)); 25 gettimeofday(&start,0); 26 //做你要做的事... 27 printf("hello world\n"); 28 gettimeofday(&stop,0
); 29 time_substract(&diff,&start,&stop); 30 printf("Total time : %d s,%d us\n",(int)diff.tv_sec,(int)diff.tv_usec); 31 }