skip to content

Clocks and Durations

std::chrono types durations and time points so seconds never mix with milliseconds, and steady_clock never jumps back. Interviewers ask which clock to time code with.

on this pageshow

explore

questions

5

In C++, which std::chrono clock should you use to measure how long an operation takes, and why not system_clock?

level: juniorimportance: must knowfreq 65%

answer

  1. wall clock versus stopwatch
  2. is_steady
  3. time points never decrease
  4. high_resolution_clock is an alias
  5. subtract, then duration_cast

basics

~20 s

Use std::chrono::steady_clock: the standard guarantees its time points never decrease and advance at a steady rate. system_clock follows the adjustable wall clock, so a clock step can make an elapsed time wrong or even negative.

solid answer

~40 s

Time an operation with `std::chrono::steady_clock`: take `now()` before and after, and the difference is a `steady_clock::duration`, which you convert with `duration_cast<milliseconds>` or into a `duration<double, std::milli>` for display. The standard defines `steady_clock::is_steady` as `true`, meaning its time points never decrease and the clock is never adjusted. `system_clock` is the system-wide wall clock: an administrator or a time-sync daemon can step it, so `now() - start` can jump or go negative. `high_resolution_clock` only promises the shortest tick period and may be an alias of either clock; libc++ aliases `steady_clock` when a monotonic clock exists, libstdc++ aliases `system_clock`, so avoid it for intervals. `system_clock` is the right clock for timestamps, since C++20 specifies its epoch as Unix time.

code

cpp · 19 lines
cpp
#include <chrono>
#include <iostream>
#include <thread>

int main() {
    using namespace std::chrono;
    std::cout << std::boolalpha
              << "steady_clock::is_steady " << steady_clock::is_steady << '\n'
              << "system_clock::is_steady " << system_clock::is_steady << '\n'
              << "high_resolution_clock is steady_clock "
              << std::is_same_v<high_resolution_clock, steady_clock> << '\n';

    const auto start = steady_clock::now();
    std::this_thread::sleep_for(milliseconds(20));        // the work being timed
    const auto elapsed = steady_clock::now() - start;     // a steady_clock::duration

    std::cout << duration_cast<milliseconds>(elapsed).count() << " ms\n";
    std::cout << duration<double, std::milli>(elapsed).count() << " ms (fractional)\n";
}

go deeper

for a junior

Recall that steady_clock is the stopwatch and system_clock is the wall clock, and that elapsed time is now() minus start.

for a middle

Explain what is_steady promises, why a stepped wall clock corrupts an interval, and why high_resolution_clock differs between libraries.

for a senior

Show how you would audit a code base for intervals and timeouts computed from system_clock and add a static_assert on is_steady in timing utilities.

for a principal

Decide which clock each subsystem uses for timestamps versus intervals, and make that a reviewed convention rather than a per-call choice.

## Three standard clocks with different promises The `<chrono>` header gives every clock the same shape: a `rep`, a `period`, a `duration`, a `time_point` type, a static `now()` and a `static constexpr bool is_steady`. What differs is the promise behind `now()`. | Clock | What the standard promises | `is_steady` | |---|---|---| | `std::chrono::system_clock` | wall clock time from the system-wide realtime clock; since C++20 its time points measure Unix time | unspecified | | `std::chrono::steady_clock` | time points never decrease as physical time advances and advance at a steady rate; the clock may not be adjusted | `true` | | `std::chrono::high_resolution_clock` | the clock with the shortest tick period; may be a synonym for `system_clock` or `steady_clock` | unspecified | A clock whose `is_steady` is `true` is a **stopwatch**. A clock that follows the operating system's wall time is a **calendar clock**, and calendar clocks get corrected. ## Why system_clock is wrong for intervals `system_clock::now()` reads the same time the operating system shows to users, and that time is **adjustable**: - a time-synchronization daemon may **step** it when it is far off, sometimes by seconds or hours; - an administrator or a container host may set it by hand; - a virtual machine restored from a snapshot may resume with a stale clock and then be corrected. If the clock steps between your two `now()` calls, `end - start` is the measured work **plus or minus the step**, and a backward step makes the duration negative. Nothing throws; the number is simply wrong. A timeout computed from such a value can fire immediately or never. ## How to time something correctly 1. Read `const auto start = std::chrono::steady_clock::now();` before the work. 2. Read `steady_clock::now()` again after it and subtract: the result is a `steady_clock::duration`, whose tick is the clock's `period` (nanoseconds in libc++ and libstdc++ on the usual platforms, but the standard leaves it unspecified). 3. Convert for reporting: `std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count()` truncates to whole milliseconds, while `std::chrono::duration<double, std::milli>(elapsed).count()` keeps the fraction. The two `now()` calls are cheap but not free, and the optimizer may move code across them; methodology for micro-benchmarks belongs to the material on benchmarks and profiling. ## The high_resolution_clock trap `high_resolution_clock` sounds like the right tool, but the standard only says it has the shortest tick period and **may be an alias** of `system_clock` or `steady_clock`. The two major libraries chose differently: - **libc++** declares `typedef steady_clock high_resolution_clock;` when a monotonic clock is available, otherwise it aliases `system_clock`; - **libstdc++** declares `using high_resolution_clock = system_clock;`. So the same source is steady on one toolchain and adjustable on another. If you need a stopwatch, name `steady_clock`; if a generic component must accept any clock, check `Clock::is_steady` with a `static_assert`. ## What system_clock is for `system_clock` is the right choice when the value must mean a moment in **civil time**: a log timestamp, a `Date` header, an expiry stored in a database, a time shown to a user. Since C++20, `sys_time` values measure the time since 1970-01-01 00:00:00 UTC excluding leap seconds, so they convert to calendar dates with `std::chrono::sys_days` and to `std::time_t` with `system_clock::to_time_t`. A `steady_clock` time point, by contrast, has an **unspecified epoch**: it is only meaningful when compared with another time point from the same clock in the same program run. ## Mistakes reviewers catch 1. **A timeout computed from `system_clock`**, such as `if (system_clock::now() - start > 5s)`. It works in every test and fails on the day the clock is corrected. 2. **Printing `count()` without the unit.** `elapsed.count()` on a `steady_clock::duration` is a number of the clock's ticks, nanoseconds in libc++ and libstdc++; logging it as milliseconds is off by a factor of a million. Convert first, or print the duration itself with C++20 stream output, which appends the unit. 3. **Storing elapsed time in an `int`.** Keep it as a `duration` until it leaves the program; the type carries the unit and the conversions are checked. 4. **Mixing clocks in one expression.** `steady_clock::now() - systemStart` does not compile, which is the good outcome; casting around the error is the bad one.

  • Can a steady_clock measurement still be distorted, even though the clock is never stepped?
    Yes, because it measures elapsed real time, not work. If the thread is descheduled or blocked, the wait is counted; the two `now()` calls cost something themselves; and a tick period coarser than the work rounds it away. The standard only promises that values never decrease and advance at a steady rate relative to real time. For CPU time rather than elapsed time you need a platform API, not a `<chrono>` clock.
  • How would you make a generic Timer<Clock> refuse a clock that can be adjusted?
    Add `static_assert(Clock::is_steady, "Timer needs a steady clock");` inside the template. Every standard clock exposes `is_steady`, and it is a constant expression, so the check costs nothing at run time and catches `Timer<system_clock>` or a `high_resolution_clock` that aliases `system_clock` at compile time.

A wall clock someone may reset versus a stopwatch that only runs forward: you time the race with the stopwatch and read the wall clock to record when it started.

  • system_clock is fine for timing because the system clock never goes backwards
  • high_resolution_clock is always the most precise steady clock
  • steady_clock::now() returns the time of day
  • the difference of two time points is an integer number of milliseconds
  • a steady_clock time point can be stored and compared after a restart

Assumes C++11 clocks; system_clock's epoch is specified as Unix time only since C++20.

open as a page

Why does std::chrono::seconds s = 1500ms; fail to compile in C++, and what does duration_cast<seconds> do with the remainder?

level: middleimportance: must knowfreq 55%

basics

~10 s

std::chrono allows an implicit duration conversion only when no precision can be lost, and 1500ms to seconds would drop 500ms. duration_cast<seconds>(1500ms) truncates toward zero to 1s; C++17's floor, ceil and round choose another direction.

open as a page

In C++ std::chrono, which arithmetic is allowed between time_points and durations, and what types do literals like 250ms and 3d produce?

level: middleimportance: should knowfreq 42%

basics

~20 s

time_point plus duration gives a time_point, and the difference of two time_points of the same clock gives a duration; adding two time_points, or mixing clocks, does not compile. Literals like 250ms make durations, while C++20's 3d and 2026y make calendar day and year values.

open as a page

With C++20's std::chrono calendar and time-zone types, how do you turn a local wall-clock time into UTC, and what happens in a DST gap?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Build a local_time from a date and a time of day, then convert it with a time_zone's to_sys or a zoned_time. A time skipped by a daylight-saving gap throws nonexistent_local_time, a repeated one throws ambiguous_local_time, unless you pass choose::earliest or choose::latest.

open as a page

A C++ gateway's rate limiter built on system_clock::now() stopped admitting requests for an hour after an NTP clock step; what went wrong, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The limiter stored its window start as a system_clock time; when the wall clock stepped back an hour, now minus start stayed negative, so the window never reset. Measure every in-process interval with steady_clock and keep system_clock for timestamps.

open as a page