clinuxtimeclock

clock() precision in time.h


I am trying to calculate the number of ticks a function uses to run and to do so using the clock() function like so:

clock_t time = clock();
myfunction();
clock_t time2 = clock() - time;
printf("time elapsed : %lu",time2);

But the problem is that the value it returns is a multiple of 10000, which I think is the CLOCKS_PER_SECOND. Is there a way or an equivalent function value that is more precise?

I am using Ubuntu 64-bit, but would prefer if the solution can work on other systems like Windows & Mac OS.


Solution

  • There are a number of more accurate timers in POSIX.

    There are other sub-second timers of greater or lesser antiquity, portability, and resolution, including:

    Do not use ftime() or times() unless there is nothing better. The ultimate fallback, but not meeting your immediate requirements, is

    The clock() function reports in units of CLOCKS_PER_SEC, which is required to be 1,000,000 by POSIX, but the increment may happen less frequently (100 times per second was one common frequency). The return value must be divided by CLOCKS_PER_SEC to get time in seconds.