Skip to content

Working with Dates and Times: The chrono Library

Beginning of the lesson

Working with Dates and Times: The chrono Library

Type-safe durations, clocks and time points for measuring and scheduling

Big Idea: Time is not just a number. A raw int holding "500" tells you nothing about whether that is 500 seconds, milliseconds, or nanoseconds - and mixing those units is a classic source of silent bugs. The <chrono> library encodes the unit in the type. A std::chrono::milliseconds is a different type from a std::chrono::seconds, so the compiler converts between them for you and refuses conversions that would silently lose precision.
By the end you will be able to:
  • explain the three core abstractions: durations, clocks and time points,
  • pick the right clock for measuring elapsed time versus reading the wall-clock date,
  • convert safely between units with duration_cast and understand when it truncates,
  • time your own code and build a small stopwatch and countdown.

1. Why measuring time is deceptively hard

Before <chrono>, people timed code with C functions such as time() or clock(), storing the result in a bare long. That approach hides three traps:

  • Unit confusion: a number like 1500 has no unit attached. Is a function that returns it giving you seconds or milliseconds? Nothing in the type tells you, so the wrong assumption compiles happily and produces a bug that is 1000x off.
  • The wrong clock: the everyday "wall clock" (your computer's calendar time) can jump. When the machine syncs with a time server, or a user changes the date, or daylight saving shifts, the wall clock can move backward. If you used it to time a task, you can get a negative or absurd duration.
  • Silent overflow and precision loss: converting seconds to nanoseconds by multiplying by a billion can overflow a 32-bit integer, and converting back by dividing can throw away the fractional part without warning.

<chrono> attacks all three by giving time a rich type system. The unit lives in the type, conversions that lose precision must be spelled out explicitly, and each clock is a distinct type with documented guarantees. Think of it as the RAII and const-correctness mindset applied to time: let the compiler enforce what you would otherwise have to remember.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers