You can use clock_gettime
, which provides a higher resolution timer.
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));
But clock cycles will more accurately reflect the execution speed of your code. You can't, as accurately, measure program speed using any measurement of time. This is because there are a lot of variables which may influence the execution time of your program:
- The number of other processes running
- The amount of available ram on your computer
- Changes in the processors clock speed
Update (for 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.
*/
}