C++ - Chrono Time & Date

Overview

Estimated time: 45–65 minutes

Measure time, schedule sleeps, and format timestamps using chrono. Learn durations, time points, clocks, and best practices.

Learning Objectives

  • Use durations and time_points with system_clock and steady_clock.
  • Convert between units safely and format time for output.

Prerequisites

Durations and conversions

#include 
#include 
int main(){
  using namespace std::chrono;
  auto ms = 1500ms;
  auto s = duration_cast(ms);
  std::cout << s.count() << "s\n"; // 1
}

Measure elapsed time

#include 
#include 
#include 
int main(){
  using namespace std::chrono;
  auto start = steady_clock::now();
  std::this_thread::sleep_for(50ms);
  auto end = steady_clock::now();
  std::cout << duration_cast(end-start).count() << "ms\n";
}

Format timestamp

#include 
#include 
#include 
int main(){
  auto now = std::chrono::system_clock::now();
  std::cout << std::format("{}\n", now);
}

Common Pitfalls

  • Using system_clock for measuring elapsed time (subject to wall-clock adjustments). Prefer steady_clock.
  • Overflow when converting durations; use duration_cast and appropriate units.

Checks for Understanding

  1. When to use steady_clock vs system_clock?
  2. How do you convert milliseconds to seconds?
Show answers
  1. Use steady_clock for measuring intervals; system_clock for wall-clock time.
  2. duration_cast(ms).

Exercises

  1. Implement a stopwatch that prints elapsed ms between two events.
  2. Print current date/time every second for five seconds.