使用clock() 函数来进行计时,时不时的返回一个很大的负数,怎么检查也检查不出错误,现在找出错误原因,给大家分享一下。
来源网页:http://kebe-jea.blogbus.com/logs/33603387.html
跑实验的时候,结果时不时出现统计时间是负数的问题……开始以为是逻辑错误,程序调了个底儿掉,没找到错误。今天突然意识到应该是计时出了问题,clock()返回的是长整数,加上linux下的CLOCKS_PER_SEC是1000000(Windows下这个数是1000,难怪原来用的时候没有发现问题),运行时间长了自然会越界,然后会滚回滚。
之后翻clock的帮助文档,发现里边写到
Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.
我每次开始记录下clock()返回值,结束时记录下,做差,记录结果,难怪会出错,而且可重复性那么差,半个小时才重现一次错误。
发现了问题,接着就得找解决方法。找来找去(其中在碧海青天C版版主同学帮助下,顺便强烈感谢) 知道了用timeval结构体能解决问题。
timeval里边有俩成员,tv_sec 的单位是秒;tv_usec 的单位是 1 / CLOCKS_PER_SEC = 0.000001秒,记录时间的时候用gettimeofday函数,下面摘自man gettimeofday
#include <sys/time.h> int gettimeofday(struct timeval *tv, struct timezone *tz); int settimeofday(const struct timeval *tv, const struct timezone *tz); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): settimeofday(): _BSD_SOURCE DESCRIPTION The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone. The tv argument is a struct timeval (as specified in <sys/time.h>): struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; and gives the number of seconds and microseconds since the Epoch (see time(2)). The tz argument is a struct timezone: struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of DST correction */ }; 这样计算时差就很容易了, timeval tv, tv1; gettimeofday(&tv, 0); //blah blah gettimeofday(&tv1, 0); cout<<(tv1.tv_sec - tv.tv_sec + (double)(tv1.tv_usec - tv.tv_usec) / CLOCKS_PER_SEC)<<endl;
转贴地址:http://blog.csdn.net/panyuequn/article/details/5046223