您可以使用clock_gettime
,它提供了更高分辨率的计时器。
struct timespec t1 = { 0, 0 },
t2 = { 0, 0 };
if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1) < 0){
perror ("Failed to get cpu time");
return -1;
}
/* test code starts here */
for (int i = 0; i < 200000000; i++); // hefty loop
/* test code ends here */
if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t2) < 0){
perror ("Failed to get cpu time");
return -1;
}
printf ("Test code took %d.%d\n",
(int)(t2.tv_sec - t1.tv_sec),
(int)(t2.tv_nsec - t1.tv_nsec));
但是时钟周期会更准确地反映代码的执行速度。您无法准确地使用任何时间测量来测量程序速度。这是因为有很多变量可能会影响程序的执行时间:
- 正在运行的其他进程数
- 您计算机上的可用内存数量
- 处理器时钟速度的变化
更新(适用于 Windows):
#include <stdio.h>
#include <windows.h>
int main (){
LARGE_INTEGER count1, count2, freq;
if (!QueryPerformanceCount (&count1)){
perror ("Couldn't get first count");
return -1;
}
for (int i = 0; i < 200000000; i++);
if (!QueryPerformanceCount (&count2)){
perror ("Couldn't get second count");
return -1;
}
if(!QueryPerformanceFrequency(&freq)){
perror ("Couldn't get processor frequency");
return -1;
}
#if ( __WORDSIZE == 64 )
#pragma message "Performing 64-bit build"
printf ("The difference is %ll\n", count2.QuadPart - count1.QuadPart);
printf ("Time (appx): %l\n", (count2.QuadPart - count1.QuadPart) / freq.QuadPart );
#else
#pragma message "Performing 32-bit build"
/* The code for 32-bit builds here is incomplete. The difference
* becomes inaccurate after the time has exceeded 32-bits. You can
* work out the math to compensate for that, or just start compiling
* for 64-bit builds. (Google "compile 64 bit visual studio").
*
*
*/
#endif
/* A processor frequency can change during a
* computationally intensive program. Therefore,
* the difference in clock ticks (above) is the most
* accurate way to measure performance.
*/
}