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
- Start with 1,500 milliseconds
- Do this Convert to whole seconds
- Result 1 second
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.
#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;
}
-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
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.
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.