Search code examples
ctimebenchmarkingtimingmicrobenchmark

Measure elapsed time in C?


So, I'd like to see how long a function of in my code takes to run. (in realtime). Originally, I had this:

clock_t begin = clock();
my_function();
clock_t end = clock();
double time_spent = (double)(end - begin);

But apparently, there are some problems with this approach.

  1. It only measures the time that the cpu took to process my application.
  2. It only measures on microsecond level, from what I can see - which isn't precise enough for my case.

So, what is the proper way to get the time a function took to run? Is CPU time really the right approach? How precise can I measure? I was thinking nanosecond level?


Solution

  • The C Standard does not define a portable way to do this. The time() library function has a definition of 1 second, which is inappropriate for your purpose. As mentioned by @Puck, C11 did introduce timespec_get() to retrieve a more precise time value, but this function is not widely supported and may not provide the expected accuracy.

    Other functions are available on selected systems:

    • The POSIX standard defines gettimeofday() and clock_gettime() which can return precise real time with the argument CLOCK_REALTIME.

    • OS/X has a more precise alternative: clock_gettime_nsec_np which returns a 64-bit value in nanosecond increments.

    • Microsoft documents this for Windows.

    Note however that performing precise and reliable sub-microsecond benchmarks is a difficult game to say the least.