clock函数返回负值~ (转)
使用clock() 函數(shù)來進(jìn)行計(jì)時,時不時的返回一個很大的負(fù)數(shù),怎么檢查也檢查不出錯誤,現(xiàn)在找出錯誤原因,給大家分享一下。
來源網(wǎng)頁:http://kebe-jea.blogbus.com/logs/33603387.html
跑實(shí)驗(yàn)的時候,結(jié)果時不時出現(xiàn)統(tǒng)計(jì)時間是負(fù)數(shù)的問題……開始以為是邏輯錯誤,程序調(diào)了個底兒掉,沒找到錯誤。今天突然意識到應(yīng)該是計(jì)時出了問題,clock()返回的是長整數(shù),加上linux下的CLOCKS_PER_SEC是1000000(Windows下這個數(shù)是1000,難怪原來用的時候沒有發(fā)現(xiàn)問題),運(yùn)行時間長了自然會越界,然后會滾回滾。
之后翻clock的幫助文檔,發(fā)現(xiàn)里邊寫到
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()返回值,結(jié)束時記錄下,做差,記錄結(jié)果,難怪會出錯,而且可重復(fù)性那么差,半個小時才重現(xiàn)一次錯誤。
發(fā)現(xiàn)了問題,接著就得找解決方法。找來找去(其中在碧海青天C版版主同學(xué)幫助下,順便強(qiáng)烈感謝) 知道了用timeval結(jié)構(gòu)體能解決問題。
timeval里邊有倆成員,tv_sec 的單位是秒;tv_usec 的單位是 1 / CLOCKS_PER_SEC = 0.000001秒,記錄時間的時候用gettimeofday函數(shù),下面摘自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 */};這樣計(jì)算時差就很容易了,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;
轉(zhuǎn)貼地址:http://blog.csdn.net/panyuequn/article/details/5046223
轉(zhuǎn)載于:https://www.cnblogs.com/wainiwann/p/4341993.html
總結(jié)
以上是生活随笔為你收集整理的clock函数返回负值~ (转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开个酒吧大概需要投资多少钱?
- 下一篇: 消除 activity 启动时白屏、黑屏