看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) win7 + code::block + gcc 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) #include <iostream> #include <ctime> #include <windows.h> #include <stdio.h> 問題(Question): 我想測試ctime的精準度 看計算執行時間的時候可以有多準 程式碼(Code):(請善用置底文網頁, 記得排版) #include <iostream> #include <ctime> #include <windows.h> #include <stdio.h> using namespace std; int main() { //cout << "Hello world!" << endl; //clock_t start, end, diff_time; clock_t start, end; double diff_time; long a; a = 0; start = clock();//開始時間 for(long i = 0; i<=1000000 ; i++) { a += i; } //cout<<c; end = clock();//結束時間 diff_time =(double) (end-start)/(double)CLOCKS_PER_SEC;//秒數 //printf("\n執行時間 = %.10f s \t %d ms\n\n",diff_time,(end-start)); a = 0; LARGE_INTEGER m_liPerfFreq={0}; QueryPerformanceFrequency(&m_liPerfFreq); LARGE_INTEGER m_liPerfStart={0}; QueryPerformanceCounter(&m_liPerfStart); for(long i = 0; i<=1000000 ; i++) { a += i; } LARGE_INTEGER liPerfNow={0}; QueryPerformanceCounter(&liPerfNow); long decodeDulation=( ((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000000)/m_liPerfFreq.QuadPart); cout.setf(ios::showpoint, ios::fixed); cout.precision (10); printf("ctime 版本\n"); printf("TIME: %.10f s \t %d ms\n\n",diff_time,(end-start)); printf("window.h 版本\n"); cout<<"TIME: "<<decodeDulation<<" Microsecond"<<endl; return 0; } 補充說明(Supplement): 我的執行結果是 ctime 版本 TIME: 0.0000000000 s 0 ms window.h 版本 TIME: 2825 Microsecond 會這樣是因為ctime的clock精準度只有到 秒 嗎? 還是說可以讓她在更精準一點呢? 謝謝大家 -- 我不是宅 我只是比較居家 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 108.6.67.134
loveme00835:diff_time 的型態是整數 01/14 05:17
我把 diff_time宣告成double ctime 版本 TIME: 0.0030000000 s 3 ms window.h 版本 TIME: 2900 Microsecond 看起來好像比較不準一點點的樣子 ※ 編輯: rock1985 來自: 108.6.67.134 (01/14 05:23)
loveme00835:是阿... 01/14 05:39
rock1985:主要是因為clock只有精準到秒的關係嗎?? 01/14 07:55
adxis:windows 可以找 timeb, _ftime_s 01/14 10:38
adxis:UNIX 則大部分都有 gettimeofday 01/14 10:38