Re: [問題] 請問c++中的 clock() 問題

看板C_and_CPP作者 (Schottky)時間11年前 (2013/09/28 19:55), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
幫你重新縮排一遍... if (iParam3>5) { for (t=0; t<1000 ;t++) { t1 = clock(); Sleep(100); printf("%f\n", (t1)/(double)(CLOCKS_PER_SEC)); } } 所以如果要 printf 顯示的是 "經過時間" 要這樣改: clock_t t_start, t_now; // 如果是 C, 這行要放在 function 開頭處 if (iParam3>5) { t_start = clock(); for (t=0; t<1000 ;t++) { Sleep(100); t_now = clock(); printf("%f\n", (t_now-t_start)/(double)(CLOCKS_PER_SEC)); } } 注意 clock() 和 Sleep() 的順序, 你原來的寫法會造成 printf 顯示的時間 lag。 這樣的寫法沒有考慮那個很尷尬的 49.7 天當機問題就是了, 精確度也不好, 所以我通常會這樣寫: LARGE_INTEGER t_start, t_now, f; if (iParam3>5) { QueryPerformanceFrequency(&f); QueryPerformanceCounter(&t_start); for (t=0; t<1000; t++) { Sleep(100); QueryPerformanceCounter(&t_now); printf("%f ms\n", (t_now.QuadPart-t_start.QuadPart)*1000.0/f.QuadPart); } } 你原來的顯示單位是用秒, 我改成以毫秒 (0.001秒) 為單位... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.137.15.188 ※ 編輯: Schottky 來自: 220.137.15.188 (09/28 20:03)

09/28 20:11, , 1F
謝謝S大^^ 我這就去TRY!! 非常感謝你^^
09/28 20:11, 1F
文章代碼(AID): #1IHiEb_e (C_and_CPP)
文章代碼(AID): #1IHiEb_e (C_and_CPP)