我如何在C中测量时间?

我想找出多长时间(大约)的代码块执行。 像这样的东西:

startStopwatch(); // do some calculations stopStopwatch(); printf("%lf", timeMesuredInSeconds); 

怎么样?

你可以在time.h中使用clock方法

例:

 clock_t start = clock(); /*Do something*/ clock_t end = clock(); float seconds = (float)(end - start) / CLOCKS_PER_SEC; 

你可以使用time.h库,特别是time和difftime函数:

 /* difftime example */ #include <stdio.h> #include <time.h> int main () { time_t start,end; double dif; time (&start); // Do some calculation. time (&end); dif = difftime (end,start); printf ("Your calculations took %.2lf seconds to run.\n", dif ); return 0; } 

(从上面链接的difftime网页改编的例子)

请注意,这个方法只能提供几秒钟的准确性 – time_t记录自UNIX纪元 (1970年1月1日)以来的秒数。

GetTickCount的()。

 #include <windows.h> void MeasureIt() { DWORD dwStartTime = GetTickCount(); DWORD dwElapsed; DoSomethingThatYouWantToTime(); dwElapsed = GetTickCount() - dwStartTime; printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000); } 

如果你不需要精彩的分辨率,你可以使用GetTickCount(): http : //msdn.microsoft.com/en-us/library/ms724408 (VS.85) .aspx (如果它不是你自己的简单诊断,然后注意,这个数字可以环绕,所以你需要处理一点算术)。

QueryPerformanceCounter是另一个合理的选择。 (这也在MSDN上描述)

我将使用Windows API的QueryPerformanceCounter和QueryPerformanceFrequency函数。 在块前后调用前者,然后减去(current – old)得到实例之间的“ticks”的数量。 用后一个函数得到的值除以得到持续时间,单位为秒。