C/C++ Arena

Step 3 of 6

chrono durations

Passing time around as a bare int invites bugs: seconds or milliseconds? <chrono> puts the unit in the type:

using namespace std::chrono_literals;
std::chrono::milliseconds t = 1500ms;
std::chrono::seconds s = 2min;                              // exact conversions are implicit
auto whole = std::chrono::duration_cast<std::chrono::seconds>(t);   // lossy ones need a cast: 1s
t += 3s;                                                    // mixed units just work: 4500ms

Converting to a coarser unit truncates (1500ms becomes 1s), so the language makes you say duration_cast explicitly. .count() gives the raw number when you really need it, for example to print.

Your turn: write std::string mmss(std::chrono::milliseconds t) that formats a round timer as M:SS (truncating the milliseconds), like 1:55 or 0:07.

Previous: Formatting your own types Next: Measuring time