C语言两个计时函数clock()和gettimeofday()

刚刚做了项测试,要用某程序在Linux平台的运行时间(需精确到ms级)上报。

一开始用的是clock()函数:

头文件:time.h

函数原型:clock_t clock(void);

功能:该函数返回值是硬件滴答数,要换算成秒,需要除以CLK_TCK或者 CLOCKS_PER_SEC。比如,在VC++6.0下,这两个量的值都是1000。

用法

   clock_t start,end;  

   start = clock();  

   //…executing…  

   end = clock();  

   printf("Used time=%f ",(double)(end-start)/CLOCKS_PER_SEC); 

但是非常奇怪,用时显示一直在1.2s左右,与直觉严重不符。原因未知。

 

后来根据参考文献(C语言中常用计时方法总结)改用gettimeofday()函数,结果就正常了,大约在10s左右。

头文件:sys/time.h

函数原型:int gettimeofday(struct timeval *tv,struct timezone *tz);

说明:其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(若不使用则传入NULL即可)。

timeval的定义为:

 struct timeval {  

  long tv_sec; // 秒数  

     long tv_usec; //微秒数  

}  

可见该函数可用于在linux中获得微秒精度的时间。

用法

   struct timeval start,end;  

   gettimeofday(&start, NULL );  

   //…executing…  

   gettimeofday(&end, NULL );  

   double timeuse = ( end.tv_sec - start.tv_sec ) + (end.tv_usec - start.tv_usec)/1000000.0;  

   printf("time=%f ",timeuse);  

原文地址:https://www.cnblogs.com/wggj/p/6913589.html