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(7)):settimeofday(): _BSD_SOURCEDESCRIPTIONThe functions gettimeofday() and settimeofday() can get and set thetime as well as a timezone. The tv argument is a struct timeval (asspecified 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 (seetime(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
轉載于:https://www.cnblogs.com/wainiwann/p/4341993.html
總結
以上是生活随笔為你收集整理的clock函数返回负值~ (转)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开个酒吧大概需要投资多少钱?
- 下一篇: 消除 activity 启动时白屏、黑屏