Ben
Ben

Reputation: 4666

real time vs. cpu time performance measure

I'm trying to do some performance measures in c++ by measuring the real elapsed time in milliseconds vs. the cpu time in milliseconds. This is how my code looks like:

auto start = std::chrono::high_resolution_clock::now();
unsigned begin = clock();

// some computationally expensive task

auto finish = std::chrono::high_resolution_clock::now();
unsigned end = clock();

(finish - start).count();

int duration = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
int cpu_duration = 1000*(end - begin)/(CLOCKS_PER_SEC);

Now I would expect the cpu time value to be lower than the system time, because the thread might be interrupted. However, the cpu time is 2-3 times higher than the real time. Am I doing something wrong or am I misunderstanding the concept of cpu time?

Upvotes: 3

Views: 7694

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

In a nutshell:

  • real-time: time as measured with a normal clock on your wall
  • cpu-time: total time the CPU(s) was/were busy

If you have more than a single cpu then their times add up, such that eg in 1 second real-time you can use 4 seconds cpu time.

cppreference's documentation on std::clock explicitly distinguishes between wall clock and cpu time :

[...]if the CPU is shared by other processes, std::clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, std::clock time may advance faster than wall clock.

For more detials see eg here.

Upvotes: 6

Related Questions