一個簡單的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。
0ms到16ms(是否爲過程CPU時間?)。請你解釋一下實際的原因。
如果我想避免這種變化,並得到像0-1毫秒一樣的輸出,那麼我該如何更改我的代碼。 (循環運行50次,但如果我運行的100或1000倍那麼時間的影響可以很容易理解。)
可能的重複[如何以毫秒分辨率獲取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
我不認爲'clock()'是非常準確的。試試'struct/time.h' –
我希望你的計算機在從'printf()'返回之前執行其他內務處理任務。 –