日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

clock函数返回负值~ (转)

發布時間:2023/11/27 生活经验 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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函数返回负值~ (转)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。