日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

clock函数返回负值~ (转)

發(fā)布時間:2023/11/27 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 clock函数返回负值~ (转) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。