使用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

最新文章

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

热门文章

  1. mysql-5.7.17的最新安装教程
  2. inline,block,inline-block解析
  3. UI- Layer的使用总结(附动画)
  4. 记录下工作中使用的pdf.js
  5. Handling CLIK AS3 Compile Error 1152 &amp; 5000
  6. SlowHTTPTest-慢速DoS攻击
  7. 定时框架quartz的一些问题总结
  8. Linq:Grouping Operators
  9. LeetCode IPO
  10. IDEA生成serialVersionUID的警告