At the top and end of my program I use clock() to figure out how long my program takes to finish. Unfortunately, it appears to take half as long as it's reporting. I double checked this with the "time" command.
My program reports: Completed in 45.86s
Time command reports: real 0m22.837s user 0m45.735s sys 0m0.152s
Using my cellphone to time it, it completed in 23s (aka: the "real" time). "User" time is the sum of all threads, which would make sense since I'm using OpenMP. (You can read about it here: What do 'real', 'user' and 'sys' mean in the output of time(1)?)
So, why is clock() reporting in "user" time rather than "real" time? Is there a different function I should be using to calculate how long my program has been running?
As a side note, Windows' clock() works as expected and reports in "real" time.
user 0m45.735s
clock()
measures CPU time the process used (as good as it can) per 7.27.2.1
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.
and not wall clock time. Thus clock()
reporting a time close to the user
time that time
reports is normal and standard-conforming.
To measure elapsed time, if you can assume POSIX, using clock_gettime
is probably the best option, the standard function time()
can also be used for that, but is not very fine-grained.
I would suggest clock_gettime
using CLOCK_MONOTONIC
for the clock.
Depending on your specific system, that should give near-microsecond or better resolution, and it will not do funny things if (e.g.) someone sets the system time while your program is running.
I would suggest that for benchmarking inside OpenMP applications you use the portable OpenMP timing function omp_get_wtime()
, which returns a double
value with the seconds since some unspecified point in the past. Call it twice and subtract the return values to obtain the elapsed time. You can find out how precise time measurements are by calling omp_get_wtick()
. It returns a double
value of the timer resolution - values closer to 0.0
indicate more precise timers.
来源:https://stackoverflow.com/questions/13351396/c-timing-in-linux-using-clock-is-out-of-sync-due-to-openmp