clock函数返回负值~ (转)
使用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()): 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()). 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, );
//blah blah
gettimeofday(&tv1, );
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
最新文章
- c/c++模板的定义和实现分开的问题及其解决方案
- IOS中程序如何进行推送消息(本地推送,远程推送)2(上)
- maven - pom.xml 聚合(父)工程 基本内容演示
- H5笔记——locaStorage和sessionStorage本地存储的一些坑
- 【Unity3D】枪战游戏—弹孔设置
- 关于JAVA那点事---i++和++i
- Hibernate从入门到精通(五)一对一单向关联映射
- 【BZOJ 1054】 [HAOI2008]移动玩具
- Qt信号槽写法
- Database Go and JSON
- python bool值要注意的一些地方
- Hama学习总结
- 替换ubuntu 14.04的源
- LIQN join on 后跟多个条件
- 【django基础补充之URL,视图,模版】
- 安装win7出现安装程序无法创建新的系统分区
- CSS Font文字样式
- Linux下彻底卸载mysql详解
- jenkins+gitlab webhooks 实现自动触发打包
- ResourceBundle与Properties读取配置文件