2017-08-31 65 views
1

一個簡單的C程序運行在Windows 10(Visual Studio中2013)C程序輸出分析

#include <time.h> 

void hello(){ 
    printf("hello world"); 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    clock_t t; 
    for (int i = 0; i<50; i++){ 
     t = clock(); 
     hello(); 
     t = clock() - t; 
     double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds 

     printf("hello() took %f ms to execute \n", time_taken * 1000); 
    } 
    getchar(); 
    return 0; 
} 

輸出:

hello worldhello() took 0.000000 ms to execute(35times) 
hello worldhello() took 17.000000 ms to execute 
hello worldhello() took 3.000000 ms to execute 
hello worldhello() took 2.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute(5 times) 
hello worldhello() took 15.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute(4 times) 
hello worldhello() took 16.000000 ms to execute 
hello worldhello() took 0.000000 ms to execute 

一些線是0.000000和一些線15.000000-17.000000

這些輸出可能與第二次運行的輸出不完全相同。但在第二/第三..運行必須有一些行包含0.000000ms和15.000000-17.000000ms。

  1. 0ms到16ms(是否爲過程CPU時間?)。請你解釋一下實際的原因。

  2. 如果我想避免這種變化,並得到像0-1毫秒一樣的輸出,那麼我該如何更改我的代碼。 (循環運行50次,但如果我運行的100或1000倍那麼時間的影響可以很容易理解。)

+2

可能的重複[如何以毫秒分辨率獲取Windows系統時間?](https://stackoverflow.com/questions/3729169/how-can-i-get-the-windows-system-time-with -millisecond分辨率)。 Windows時間戳和定時器的分辨率爲16ms,除非您使用'timeBeginPeriod(1)'。爲了計時,無論如何你應該使用'QueryPerformanceCounter'。如果您使用的是Windows 8或更新版本,並且需要精確的當前時間,請使用'GetSystemTimePreciseAsFileTime'。 – Groo

+0

我不認爲'clock()'是非常準確的。試試'struct/time.h' –

+2

我希望你的計算機在從'printf()'返回之前執行其他內務處理任務。 –

回答

2

你的代碼是太短clock()並沒有要求的精度精確衡量的執行時間。添加到系統開銷執行時鐘測量,並且您得到隨機結果。

爲了獲得更好的效果,請在函數上循環100萬次,然後將時鐘&除以100萬以獲得平均執行時間。

對於更復雜的程序,使用代碼探查可能是一個更好的解決方案(其是專業的測量的當前功能的指令的執行時間,而不是一個簡單的任務功能&細粒時鐘)

1

1) 這是由於過程的頻率不是恆定的。

所以當你通過一個循環打印時,它直接依賴於處理器的頻率。

2)爲了避免這種情況,您可以檢查時鐘值是否恰好超過1 ms或1 s,以便此時精確打印。 (在無限循環中)

1

我同意讓 - 弗朗索瓦法布爾和本傑明奧代特。您可以使用google_benchmark來測試某段代碼的性能。它將執行一個循環,以解決運行時差異。顯示平均值和偏差。