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));
ただし、クロック サイクルは、コードの実行速度をより正確に反映します。時間の測定を使用してプログラムの速度を正確に測定することはできません。これは、プログラムの実行時間に影響を与える変数が多数あるためです。
- 実行中の他のプロセスの数
- コンピューターで使用可能な RAM の量
- プロセッサのクロック速度の変化
更新 (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.
*/
}