Library contents

C++ std::chrono::duration_cast

std::chrono::duration_cast converts between duration types. An integral destination truncates fractional units toward zero.

A simple example

std::chrono::duration_cast

  1. Start with 1,500 milliseconds
  2. Do this Convert to whole seconds
  3. Result 1 second
The 500 milliseconds left after the first second are discarded by the integral conversion.

Syntax

C++ syntax
std::chrono::duration_cast<std::chrono::seconds>(delay)
Run this example in C++

Save the program as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Convert a signed delay to whole seconds

A scheduler receives durations in one unit but reports or retries in another. Track the whole units and any fractional part before turning the original delay into a displayed time or retry budget.

First output line-1
lesson.cpp
#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono;
    milliseconds delay{-1500};
    std::cout << duration_cast<seconds>(delay).count() << '\n';
    std::cout << floor<seconds>(delay).count() << '\n';
    return 0;
}
Output
-1
-2

For a negative delay, truncation and rounding down differ. Comparing duration_cast with chrono::floor makes the distinction visible when bucketing timestamps.

C++ working draft for std::chrono::duration_cast

Advertisements

Time a school animation

A student’s animation runs for 3750 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.

Given3750 ms → whole seconds
Worked result3

Time a ticket scan

A fast ticket scan takes 820 milliseconds. Convert the elapsed milliseconds to complete seconds. Leave the fractional second out of the display.

Given820 ms → whole seconds
Worked result0