I am trying to calculate the runtime of an algorithm in linux C. I am using clock_t struct to calculate the runtime as follows:
clock_t t,start,
start=clock();
//code
t=clock()-start;
printf("Time Taken=%f msec\n",(((double)t/CLOCKS_PER_SEC)*1000.00);
The problem is I am not getting the runtime as expected (it is much less than expected). Moreover, the runtime is always in a multiple of 10 which is pretty abnormal. Also it keeps varying by a large factor. Is there any accurate method in C to calculate the runtime?
In Linux the most accurate timers are generally
clock_gettime with CLOCK_MONOTONIC, this measures wallclock with nanosecond resolution if you have a new enough kernel.
getrusage, measures CPU cycles spent by a process, IIRC at a frequency determined by the kernel tick frequency (jiffies), thus typically 1-10 ms resolution. This is in practice what you’ll get with clock() as well, except getrusage gets you the time broken down into user+sys components, you can specify whether you want child time included etc.
As jpalecek mentions, clock_gettime with CLOCK_PROCESS_CPUTIME_ID should give you high-resolution process time, (though I’ve never used it myself).