9

I measure cpu time and wall time of sorting algorithms on linux. Im using getrusage to measure a cpu time and clock_gettime CLOCK_MONOTONIC to get a wall time. Althought I noticed that a cpu time is bigger than wall time - is that correct? I always thought that cpu time MUST be less than wall time. My example results:

3.000187 seconds  [CPU]
3.000001 seconds  [WALL]
mazix
  • 2,540
  • 8
  • 39
  • 56

2 Answers2

15

If a computation requires two seconds of processor time, then two processors can (ideally) complete it in one second. Hence a two-processor system has two CPU seconds for every wall-clock second. Even if you do not use multi-threading explicitly in your process, a library you use or the operating system may use multiple processors to perform work for your process.

Additionally, some of the accounting is approximate. A system might track processor time in some small unit, say microseconds for the purpose of argument, and charge a process for a microsecond anytime the process receives at least half a microsecond of processor time. (Which should be a lesson to all the people who answer floating-point questions with recommendations to use integer arithmetic to avoid rounding errors. All discrete arithmetic can have rounding errors.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

Depending on the argument you use, getrusage may return the sum of CPU time across all threads in your process. If you have more than one thread this can cause the CPU time to be higher than the wall clock time.

Also, while the result structure stores the values in microseconds, the actual precision may be much lower than that, hence the small discrepancy.

Benawii
  • 133
  • 4
  • I use it like this: `getrusage(RUSAGE_SELF, &rus)` and have only one thread: (`int main(){//...}`) – mazix Jul 24 '13 at 20:24
  • Then it is probably due to limited precision of `getrusage`. You can try running the program several times to see how both values vary. – Benawii Jul 24 '13 at 20:35