Search code examples
c++11clockc++-chrono

Difference in time measured by clock and steady_clock


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?


Solution

  • 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.