Time and clocks with std::chrono
Measure elapsed time and represent durations and time points with the type-safe chrono library.
Learning objectives
- Distinguish a
std::chrono::durationfrom astd::chrono::time_point. - Use
steady_clockto measure elapsed time andsystem_clockfor wall-clock timestamps. - Convert durations with
duration_castand explain when integral conversions truncate. - Use chrono literals with the correct language-version support.
Prerequisites: functions, numeric types, and basic duration arithmetic. Review Functions and Numeric types first. Examples use C++11 or later, with chrono literals requiring C++14.
Representing time safely
std::chrono represents durations and time points with types. This is safer than storing every time value as an unexplained integer because the type communicates the unit and prevents many accidental unit mix-ups.
Measure elapsed time
#include <chrono>
#include <iostream>
#include <thread>
int main() {
using clock = std::chrono::steady_clock;
auto start = clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(120));
auto finish = clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start);
std::cout << elapsed.count() << " ms\n";
}Use steady_clock for measuring intervals because it is monotonic: its time does not jump backwards due to wall-clock adjustments. system_clock represents the system's wall-clock time and is useful for calendar timestamps.
Durations and conversions
using namespace std::chrono; using namespace std::chrono_literals; // C++14 auto short_wait = 250ms; // C++14 chrono literal, with using namespace std::chrono_literals; auto seconds = duration_cast<std::chrono::seconds>(short_wait);
For the literal suffixes, add using namespace std::chrono_literals; in the relevant scope. Converting from a smaller unit to a larger integral unit may truncate: 250 milliseconds becomes 0 whole seconds. Choose a suitable representation before converting.
Time points
A time_point is a point on a clock's timeline. Subtracting two compatible time points produces a duration. Do not mix clock domains casually; a system-clock timestamp and a steady-clock measurement serve different purposes.
Common mistakes
- Using system_clock to benchmark code that needs a monotonic clock.
- Assuming duration_cast rounds rather than truncates.
- Comparing values with different units after stripping away their chrono types.
- Assuming a sleep call wakes at an exact deadline; scheduling delays can make it late.
Practice
- Which clock is appropriate for benchmarking an operation?
- What is the result of converting 1500 milliseconds to integral seconds?
- What does subtracting two time_points produce?
Show answers
- steady_clock.
- 1 second, because the fractional part is truncated.
- A duration.
Summary
Use chrono durations for units, time_points for moments, steady_clock for elapsed-time measurement, and system_clock for wall-clock timestamps.