C++程序中通常需要计时来评估性能及耗时。耗时可以帮助我们分配计算资源,找到优化重点。
实验背景:
在多线程的C++程序中,使用clock计时和gettimeofday计时的数据不一致,那么,哪个函数统计了正确的数据呢?它们分别统计的是什么数据呢?
原答案:measure-time-in-linux-time-vs-clock-vs-getrusage-vs-clock-gettime-vs-gettimeof
前提知识:
wall time (wall-clock time):直译为墙上的时间,指挂在墙上的时钟显示的时间。wall time通常与时区相关,不同时区数值不同,所以不能直接用来做耗时统计,通常用两个wall time的相差值来统计。
clock():
clock返回的是用户时间和系统时间的总和。过去的版本中,clock是用来统计CPU的cycle数的;而更新的版本中,要求每秒包含的clock数(CLOCKS_PER_SEC)为1,000,000,则clock统计出的精度为1µs(微秒)。
gettimeofday():
gettimeofday返回的是精度为µs的wall-clock time。POSIX.1-2008建议,应用应该使用clock_gettime() 接口而不是gettimeofday()。
结论:
在多线程情况下,clock统计的是用户和系统时间的总和,会比实际的程序耗时多出额外的统计;
用gettimeofday获取不同时间段的wall time,然后做差可以得出精确为微秒的耗时,示例代码如下:
struct timeval start, end;
gettimeofday(&start, NULL);
test();
gettimeofday(&end, NULL);
int64_t abs_timediff = (end.tv_sec - start.tv_sec) * 1000ULL * 1000ULL + end.tv_usec - start.tv_usec;
double sec_timediff = (double)abs_timediff / 1000000;
cout << "Time cost of test() is: " << sec_timediff << "s." << endl;
而官方标准推荐使用clock_gettime,这个待研究。