5

I was trying to measure the time taken to execute a specific function in my code. Initially I used the clock() function as below

clock_t start = clock();
do_something();
clock_t end = clock();

printf("Time taken: %f ms\n", ((double) end - start)*1000/CLOCKS_PER_SEC);

Later I was reading about the chrono library in C++11 and tried to measure the same with a std::chrono::steady_clock as below

using namespace std::chrono;

auto start = steady_clock::now();
do_something();
auto end = steady_clock::now();
printf("Time taken: %lld ms\n", duration_cast<milliseconds>(end - start).count());

The time measured by the first code snippet (using clock) was 89.53 ms and that measured by steady_clock was 1140 ms.

Why is there such a big difference in time measured by both the clocks?

2

1 Answer 1

6

clock measures processor time, whereas steady_clock measures physical time. So you can get differences like this if do_something() was preempted by other processes (such as checking mail or whatever).

Daniel H makes a great point below in the comments that this can also happen if do_something() isn't CPU bound. For example if it sleeps, blocks on locking a mutex, waits on a condition variable, etc.

4
  • 2
    That would also show up id do_something isn’t CPU bound, right?
    – Daniel H
    Commented Jun 12, 2017 at 18:11
  • @DanielH: Thanks Daniel, good point. I've added your comment to my answer. Commented Jun 12, 2017 at 20:20
  • @HowardHinnant What would be the correct approach to measure time taken by a function that can sleep, blocks on a mutex etc? Commented Jun 13, 2017 at 6:40
  • 1
    @nangal.vivek: There is no one right answer. It depends on what you want to measure. If you want to measure how long a function takes, use steady_clock. If you want to measure how many CPU cycles are consumed by your function, use clock. I find myself using steady_clock more often because I'm usually interested in the elapsed time a function takes. Commented Jun 13, 2017 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.