2

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.

Community
  • 1
  • 1
DemiImp
  • 968
  • 8
  • 18
  • C++ doesn't belong in the title of the question. And, as you formunlate your question this has not much to do with C++. – Jens Gustedt Nov 12 '12 at 21:11

3 Answers3

6

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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • How is this different from what the OP wrote? – Pubby Nov 12 '12 at 20:58
  • Since the question is tagged C++ one option for timing is the standard C++ library ``, for example `std::high_resolution_clock` or `std::steady_clock`. – bames53 Nov 12 '12 at 21:14
2

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.

Nemo
  • 70,042
  • 10
  • 116
  • 153
0

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.

Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186