1

I have seen many posts about using the clock() function to determine the amount of elapsed time in a program with code looking something like:

start_time = clock();

//code to be timed
.
.
.

end_time = clock();
elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

The value of CLOCKS_PER_SEC is almost surely not the actual number of clock ticks per second so I am a bit wary of the result. Without worrying about threading and I/O, is the output of the clock() function being scaled in some way so that this divison produces the correct wall clock time?

Timulus
  • 334
  • 3
  • 12
  • 1
    Welcome to Stack Overflow! Make sure you tag your question with the right language – people often add tags they know about to their list of favourite tags, meaning the right people will be able to see this. – Rich Bradshaw Sep 02 '11 at 16:56
  • You probably know this already, but keep in mind that almost all new processors scale CPU frequency dynamically based on load - many times per second. Actual clocks per second is not a constant number. – evilspoons Sep 02 '11 at 17:09

1 Answers1

2

The answer to your question is yes.

clock() in this case refers to a wallclock rather than a CPU clock so it could be misleading at first glance. For all the machines and compilers I've seen, it returns the time in milliseconds since I've never seen a case where CLOCKS_PER_SEC isn't 1000. So the precision of clock() is limited to milliseconds and the accuracy is usually slightly less.

If you're interested in the actual cycles, this can be hard to obtain. The rdtsc instruction will let you access the number "pseudo"-cycles from when the CPU was booted. On older systems (like Intel Core 2), this number is usually the same as the actual CPU frequency. But on newer systems, it isn't.

To get a more accurate timer than clock(), you will need to use the hardware performance counters - which is specific to the OS. These are internally implemented using the 'rdtsc' instruction from the last paragraph.

Mysticial
  • 464,885
  • 45
  • 335
  • 332