The Original Program
I was writing a program recently; the pseudocode was roughly like this.
1 | start = get_time(); |
We all know that we’ve previously used the clock() function to get a program’s runtime.
For example:
1 | clock_t start = clock(); |
A Problem in the Program
In the program I used the clock() function the same way, and the result was disappointing: extremely low program efficiency (perhaps my interval was too short, causing repeated calls).
- In my program the 1s interval needs to be fairly precise — the previous operation and this one must truly be 1s apart.
clock()only counts CPU running time; if the program sleeps, no CPU time is consumed. That is to say, the interval measured byclock()may be a bit longer than the real time — and as for how much longer, I don’t know how to compute that either.
My Experiment
1 |
|
If sleep(2) is called, clock() barely changes, which shows that in the sleeping state
the CPU clock is not consumed.
Correct Time Measurement
For polling timers, I recommend the clock_gettime() function.
1 | struct timespec start, finish; |
The code above can be seen in the gist.