Measure elapsed time in C?

Viewed 528

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?

2 Answers

So, you should ask yourself if you really need nanosecond level. A processor run with a clock rate in the GHz order, meaning an instruction takes in the order of nanosecond to be executed. This means that nanosecond accuracy is extremely complicated (if not impossible) to measure.

There is new timespec_get that comes with C11 that can get you time with nanosecond resolution, but it is certainly not that accurate.

If your goal is to measure execution time of a function, your best option is certainly to call your function in a loop that executes it like a thousand times and you measure it with microsecond accuracy, this would certainly be closer to nanoseconds accuracy than any timer that claim to be nanoseconds.

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.

Related