C/C++ Arena

Step 4 of 6

Measuring time

<chrono> has several clocks, and picking the wrong one is a classic bug:

Clock Use it for
std::chrono::steady_clock measuring elapsed time: it never jumps backwards
std::chrono::system_clock wall-clock time ("now" as a date); can jump when the OS adjusts the time

Timing code with system_clock can give negative durations if the clock is corrected mid-measurement. Always use steady_clock for intervals, timeouts and benchmarks:

auto start = std::chrono::steady_clock::now();
work();
auto elapsed = std::chrono::steady_clock::now() - start;   // a duration

Your turn: write template <typename F> std::chrono::microseconds time_it(F&& f) that calls f() once and returns how long it took.

Previous: chrono durations Next: Strict number parsing with from_chars