0Pricing
C++ Academy · Lesson

Durations and Clocks

Measure time intervals.

Why <chrono>?

The <chrono> library gives C++ a type-safe way to work with time. Instead of raw integers, you use strongly typed durations and time points so the compiler catches unit mistakes.

  • No more mixing up seconds and milliseconds.
  • Units are part of the type system.
#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono;
    seconds s{5};
    std::cout << "Duration: " << s.count() << " seconds\n";
    return 0;
}

What Is a Duration?

A std::chrono::duration represents a span of time. It stores a count of ticks plus a ratio describing the tick period. Predefined aliases cover common units.

  • hours, minutes, seconds
  • milliseconds, microseconds, nanoseconds
#include <iostream>
#include <chrono>

int main() {
    using namespace std::chrono;
    milliseconds ms{1500};
    std::cout << ms.count() << " ms\n";
    return 0;
}

All lessons in this course

  1. Durations and Clocks
  2. Time Points
  3. Measuring Code Performance
  4. Calendar and Time Zones
← Back to C++ Academy