skip to content

Vocabulary Types

optional, expected, variant, tuple and chrono give C++ code a shared way to say maybe, result, one-of, several and time. Interviewers ask when each one fits.

on this pageshow

explore

questions

21

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

In C++17, how should a config lookup function return a value that may be missing, and how does the caller read it?

level: juniorimportance: must knowfreq 68%

basics

~10 s

Return std::optional<T>: return the found value, or std::nullopt when the key is missing. The caller tests it with has_value() or if (opt), reads it with *opt, or takes a default with value_or(fallback).

open as a page

In C++, how do you read the elements of a std::pair and a std::tuple, and when does std::get by type fail to compile?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A std::pair has the members first and second; a std::tuple is read with std::get<0>(t) or, since C++14, std::get<T>(t). Both resolve at compile time: an index past the end, or a type that occurs twice, does not compile.

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++, what happens when code calls value() versus operator* on an empty std::optional, and which belongs in production code?

level: middleimportance: must knowfreq 60%

basics

~20 s

value() checks and throws std::bad_optional_access when the optional is empty; operator* and operator-> carry an unchecked precondition, so dereferencing an empty optional is undefined behaviour in C++23. Check first and dereference, or use value() or value_or.

open as a page

Which three kinds of types can a C++ structured binding unpack, and what does each kind require of the type?

level: middleimportance: must knowfreq 60%

basics

~20 s

Structured bindings unpack arrays by element, tuple-like types through std::tuple_size, std::tuple_element and get<i>, and other classes through their non-static data members, which must be accessible and declared in one class. The number of names must match.

open as a page

In C++, how does std::visit with the overloaded-lambdas idiom handle every alternative of a std::variant, and what goes wrong with it?

level: middleimportance: must knowfreq 58%

basics

~20 s

std::visit calls the visitor with the active alternative. The overloaded idiom builds one visitor from several lambdas by inheriting their call operators, so a missing case fails to compile; implicit conversions and catch-all generic lambdas can still route alternatives silently.

open as a page

In C++17, how do you find out which alternative a std::variant holds and read it without risking an exception?

level: juniorimportance: should knowfreq 52%

basics

~10 s

Ask index() for the zero-based alternative or holds_alternative<T>(v) for a type test, then read with std::get_if<T>(&v), which returns nullptr on a mismatch. std::get<T>(v) throws std::bad_variant_access when v holds another alternative.

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

In C++23, how does a function returning std::expected<T, E> report a failure, and how does the caller read the error?

level: middleimportance: should knowfreq 50%

basics

~10 s

It returns std::unexpected(err), which constructs the expected in its error state; a plain T converts to the success state. The caller tests has_value() or if (r), reads *r or r.error(), and value() throws std::bad_expected_access<E>.

open as a page

In C++17, how does std::apply call a function with a tuple's elements, and why does passing an overloaded function name fail?

level: middleimportance: should knowfreq 35%

basics

~20 s

std::apply(f, t) calls f with get<0>(t), get<1>(t) and so on, expanded from an index sequence. An overloaded function name has no single type, so apply's callable parameter cannot be deduced; wrap the call in a lambda.

open as a page

When should a C++ function return a named struct instead of a std::tuple such as std::tuple<int, std::string, double>?

level: middleimportance: should knowfreq 50%

basics

~20 s

Return a named struct whenever callers will read the fields by meaning: status, payload and latencyMs say what get<0>, get<1> and get<2> do not. Structs still unpack with structured bindings; keep tuples for generic code that builds or forwards values by position.

open as a page

In C++17, what can a std::any hold, and how does std::any_cast behave when the requested type does not exactly match?

level: middleimportance: should knowfreq 32%

basics

~20 s

std::any holds one value of any copy-constructible type. std::any_cast<T> must name the exact stored type: the value form throws std::bad_any_cast on a mismatch, and the pointer form any_cast<T>(&a) returns nullptr. No conversions apply, so int is not long.

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

In C++23, how do and_then, transform, or_else and transform_error chain std::expected steps, and what must each callable return?

level: seniorimportance: should knowfreq 40%

basics

~20 s

and_then calls f(value) and f must return an expected with the same error type; transform wraps a plain result; or_else calls f(error) and must return an expected with the same value type; transform_error maps the error. Errors skip value steps.

open as a page

How does std::tie give a C++ Version struct a lexicographic operator<, and what does C++20's defaulted operator<=> change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

std::tie builds tuples of references to the members, and tuple comparison is lexicographic, so tie(a.major, a.minor) < tie(b.major, b.minor) compares in order without copying. C++20 replaces the idiom with a defaulted operator<=> that compares members in declaration order.

open as a page

When can a C++ std::variant become valueless_by_exception, and what do index(), std::get and std::visit do afterwards?

level: seniorimportance: should knowfreq 33%

basics

~10 s

A variant may become valueless when a type-changing emplace or assignment throws after the old alternative was destroyed. Then index() returns std::variant_npos, and std::get and std::visit throw std::bad_variant_access until a new value is assigned.

open as a page

For a JSON value type in C++, when should you model it as a std::variant instead of a virtual class hierarchy, and what does each choice cost?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Use std::variant when the set of kinds is closed, like JSON's six kinds: values live in place without per-node heap allocation, and visitation flags missing cases. Use a virtual hierarchy when new kinds must be added independently.

open as a page

For a new C++ library's error-return convention, when should its API return std::expected rather than throw exceptions or return error codes?

level: principalimportance: should knowfreq 32%

basics

~10 s

Return std::expected for failures a direct caller routinely handles, such as parse or validation errors, and where exceptions are disabled; throw for rare failures handled far away and in constructors; std::expected requires C++23 consumers.

open as a page

In C++26, what does std::optional<T&> do on assignment and on construction from a temporary, and why was it ill-formed before?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

C++26 adds a partial specialization std::optional<T&> that stores a pointer: assignment rebinds it to another object instead of writing through, and construction from a temporary is deleted. Before C++26 a reference was not a valid contained type.

open as a page