skip to content

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%

answer

  1. implicit means lossless
  2. the period ratio must divide exactly
  3. floating-point reps accept anything
  4. truncation toward zero
  5. floor, ceil, round

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.

solid answer

~40 s

A `duration` converting constructor is constrained: it accepts a source only if the target `rep` is floating-point, or the source `rep` is integral and `ratio_divide<SourcePeriod, TargetPeriod>::den` is 1, meaning every source tick is a whole number of target ticks. So `milliseconds ms = 2s;` compiles and `seconds s = 1500ms;` does not, by design. `duration_cast` performs the conversion anyway with `static_cast` and integer division, so it **truncates toward zero**: `1999ms` becomes `1s` and `-1500ms` becomes `-1s`. C++17 added `floor` (toward negative infinity, `-2s`), `ceil` (toward positive infinity) and `round` (nearest, ties to even, so `2500ms` becomes `2s`). Converting to `duration<double>` keeps the fraction and is implicit. Mixed arithmetic such as `1s + 250ms` yields the common type, `milliseconds`.

code

cpp · 22 lines
cpp
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    using namespace std::chrono_literals;

    milliseconds ms = 2s;                         // lossless, so implicit
    duration<double> fractional = 1500ms;         // floating-point rep, so implicit
    // seconds s = 1500ms;                        // ill-formed: would drop 500ms

    std::cout << ms.count() << ' ' << fractional.count() << '\n';          // 2000 1.5
    std::cout << duration_cast<seconds>(1999ms).count() << ' '             // 1
              << duration_cast<seconds>(-1500ms).count() << '\n';          // -1
    std::cout << floor<seconds>(-1500ms).count() << ' '                    // -2
              << ceil<seconds>(1001ms).count() << ' '                      // 2
              << round<seconds>(1500ms).count() << ' '                     // 2
              << round<seconds>(2500ms).count() << '\n';                   // 2: ties to even

    auto total = 1s + 250ms;                      // common type is milliseconds
    std::cout << total.count() << '\n';           // 1250
}

go deeper

for a junior

Recall that chrono converts coarse to fine units implicitly and needs duration_cast to go from fine to coarse.

for a middle

Explain the lossless-conversion constraint, truncation toward zero in duration_cast, and how floor, ceil and round differ.

for a senior

Show how you would choose the rounding a business rule needs and design timeout parameters so unit mistakes fail to compile.

for a principal

Set the convention for durations at module boundaries, such as one canonical unit per interface and no raw integer timeouts.

## A duration is a count plus a unit `std::chrono::duration<Rep, Period>` stores one number, the **tick count** of type `Rep`, and carries the unit in its type as a `std::ratio` of seconds. `std::chrono::milliseconds` is a duration with period `std::milli`, `std::chrono::seconds` one with period `1`. The standard aliases only promise a minimum width for the count: `nanoseconds` uses a signed integer of at least 64 bits, `seconds` at least 35 bits, `hours` at least 23. With a 64-bit count, `nanoseconds` spans roughly ±292 years. ## The implicit-conversion rule The converting constructor `duration(const duration<Rep2, Period2>&)` participates only when **one** of these holds: 1. the **target** `rep` is floating-point (`std::chrono::treat_as_floating_point_v<rep>` is `true`); or 2. `ratio_divide<Period2, period>::den` is `1` **and** the **source** `rep` is not floating-point. The second condition means one source tick is a whole number of target ticks. The standard's own note says the rule exists to **prevent implicit truncation errors**. | Source | Target | Implicit? | Why | |---|---|---|---| | `2s` | `milliseconds` | yes | 1 s is exactly 1000 ms | | `1500ms` | `seconds` | no | 1 ms is 1/1000 s, so 500 ms would be lost | | `90s` | `minutes` | no | 1 s is 1/60 min | | `1500ms` | `duration<double>` | yes | floating-point target keeps 1.5 | | `duration<double>(1.5)` | `seconds` | no | floating-point source into an integral target | Apple clang 21 rejects `std::chrono::seconds s = 1500ms;` with "no viable conversion from 'duration<[...], ratio<[...], 1000>>' to 'duration<[...], ratio<[...], 1>>'". ## duration_cast: explicit and truncating `std::chrono::duration_cast<ToDuration>(d)` converts any duration to any other. Its specification computes the result with `static_cast` and a multiplication or division in the widest common integer type, then casts to the target `rep`. Integer division in C++ **truncates toward zero**, so: - `duration_cast<seconds>(1999ms)` is `1s`; - `duration_cast<seconds>(-1500ms)` is `-1s`, not `-2s`; - a cast to a narrower `rep` can **overflow** when the value does not fit, and the standard performs no check. ## floor, ceil and round (C++17) C++17 added three functions with the same shape as `duration_cast` that pick the direction explicitly: - `std::chrono::floor<seconds>(-1500ms)` is `-2s`, the greatest representable value not greater than the input; - `std::chrono::ceil<seconds>(1001ms)` is `2s`, the least representable value not less than the input; - `std::chrono::round<seconds>(1500ms)` and `round<seconds>(2500ms)` are both `2s`: `round` picks the nearest value and breaks a tie toward the **even** result. `round` is constrained to integral target `rep`s. The same three exist for `time_point`, which matters when bucketing timestamps into windows: `floor<minutes>(tp)` is the start of the minute containing `tp` even before 1970, where `time_point_cast`, the time-point counterpart of `duration_cast`, would round toward the epoch instead. ## Arithmetic across units Adding or comparing durations with different periods is always allowed without a cast, because the library converts both to their **common type**, the coarsest unit that represents both exactly. `1s + 250ms` is `milliseconds(1250)`, and `1min + 30s` is `seconds(90)`. That is why chrono code rarely needs casts until it must hand a plain number to an interface that expects one, such as a configuration value in whole seconds. ## Why it matters in interviews Interviewers use this to see whether a candidate thinks in **types rather than integers**: a function taking `std::chrono::milliseconds timeout` accepts `2s` and refuses `1500us`, so the unit mistake that plagues `int timeoutMs` APIs becomes a compile error. The follow-up is usually about which rounding a business rule needs, for example rounding a billing duration up with `ceil` instead of silently truncating it with `duration_cast`. ## Mistakes reviewers catch - **`duration_cast` used as rounding.** A request that took 1999 ms is reported as 1 s; a timeout of 999 ms becomes 0 s and fires immediately. Pick `round` or `ceil` when the direction matters. - **`.count()` too early.** Extracting the number before arithmetic throws away the unit, and the next line multiplies milliseconds by a factor meant for seconds. - **Floating-point durations everywhere.** `duration<double>` converts implicitly from anything, which is convenient for display but makes equality comparisons and accumulation inexact; keep integral durations for logic. - **Overflow on the way down to fine units.** `duration_cast<nanoseconds>(hours::max())` cannot fit; keep values in the coarsest unit that holds them.

  • How do you write a function that accepts a timeout in any unit without losing precision?
    Take the finest unit you need, for example `void wait_for(std::chrono::milliseconds timeout)`. Callers pass `2s` or `250ms` and the coarser values convert implicitly; a finer value such as `1500us` is rejected, so the caller must choose `duration_cast`, `floor`, `ceil` or `round` explicitly. A function template over `duration<Rep, Period>` is the alternative when you must preserve every unit.
  • Why is round<seconds>(2500ms) equal to 2s rather than 3s?
    The standard specifies that when two representable values are equally close, `round` returns the one whose count is even. Ties-to-even avoids the upward bias that always rounding halves away from zero would add to a sum of many rounded values. `round` also requires an integral target `rep`; for a floating-point target there is nothing to round.

  • duration_cast rounds to the nearest value
  • seconds s = 1500ms; compiles and stores 1
  • duration_cast<seconds>(-1500ms) gives -2s
  • round on durations rounds halves away from zero
  • adding seconds and milliseconds needs a duration_cast first

Assumes C++17 for floor, ceil and round on durations; the implicit-conversion rule and duration_cast date from C++11.