Skip to content
C++

std::chrono Quick Reference

C++ chrono cheat sheet — durations, clocks, time points, arithmetic, formatting, calendars (C++20), time zones, and benchmarking patterns.

Durations

cpp
#include <chrono>
using namespace std::chrono_literals;

// Predefined duration types
std::chrono::nanoseconds  ns{100};
std::chrono::microseconds us{100};
std::chrono::milliseconds ms{100};
std::chrono::seconds      s{30};
std::chrono::minutes      min{5};
std::chrono::hours        h{2};
// C++20:
std::chrono::days         d{7};
std::chrono::weeks        w{2};
std::chrono::months       mo{3};
std::chrono::years        y{1};

// Literals (using namespace std::chrono_literals)
auto t1 = 100ns;
auto t2 = 500us;
auto t3 = 250ms;
auto t4 = 30s;
auto t5 = 5min;
auto t6 = 2h;

// Arithmetic
auto total = 1h + 30min + 15s;         // 1:30:15
auto doubled = 2 * 30s;                 // 60s
auto half = 10min / 2;                  // 5min

// Conversion (explicit — may lose precision)
auto ms_from_s = std::chrono::duration_cast<std::chrono::milliseconds>(30s);
// ms_from_s.count() == 30000

// Get raw value
s.count();  // 30

// High-res duration from double
std::chrono::duration<double> dt{1.5};  // 1.5 seconds
std::chrono::duration<double, std::milli> dt_ms{1500.0}; // 1500ms as double

Clocks

cpp
// system_clock — wall clock (may be adjusted, has epoch = Unix epoch)
auto now_sys = std::chrono::system_clock::now();

// steady_clock — monotonic (never goes backward), for measuring elapsed time
auto now_steady = std::chrono::steady_clock::now();

// high_resolution_clock — usually == steady_clock or system_clock
auto now_hi = std::chrono::high_resolution_clock::now();

// utc_clock (C++20) — UTC with leap seconds
auto now_utc = std::chrono::utc_clock::now();

// tai_clock, gps_clock (C++20) — other epoch-based clocks

Rule: use steady_clock for measuring intervals; use system_clock for wall-clock time.


Time Points

cpp
auto tp = std::chrono::steady_clock::now();

// Arithmetic with time points
auto later = tp + 5s;
auto elapsed = later - tp;  // duration

// Convert to duration since epoch
auto since_epoch = tp.time_since_epoch();
auto ms_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(since_epoch);

// Convert system_clock to time_t (for C interop)
auto sys_tp = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(sys_tp);

Benchmarking

cpp
auto start = std::chrono::steady_clock::now();

expensive_operation();

auto end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::println("took {} μs", elapsed.count());

// Or as floating-point seconds
std::chrono::duration<double> dt = end - start;
std::println("took {:.3f} s", dt.count());

// RAII timer
struct Timer {
    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    std::string label;
    ~Timer() {
        auto us = std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::steady_clock::now() - start).count();
        std::println("[{}] {} μs", label, us);
    }
};

{
    Timer t{"my_operation"};
    do_work();
}  // prints elapsed time on destruction

Formatting (C++20)

cpp
#include <chrono>
#include <format>

auto now = std::chrono::system_clock::now();

// Format with std::format
std::println("{:%Y-%m-%d %H:%M:%S}", now);          // 2025-01-15 14:30:00
std::println("{:%H:%M}", now);                       // 14:30
std::println("{:%A, %B %d, %Y}", now);               // Wednesday, January 15, 2025

// C++23: std::print directly
std::println("now: {}", now);  // implementation-defined format

// Duration formatting
auto d = 2h + 30min + 15s;
std::println("{}", d);  // 9015s (in seconds by default)
std::println("{:%H:%M:%S}", d);  // 02:30:15

Calendar Types (C++20)

cpp
#include <chrono>
using namespace std::chrono;

// Year, month, day
year_month_day today = floor<days>(system_clock::now());
std::println("{}", today);  // 2025-01-15

year_month_day birthday{year{1990}, month{6}, day{15}};
std::println("Year: {}, Month: {}, Day: {}",
             (int)birthday.year(),
             (unsigned)birthday.month(),
             (unsigned)birthday.day());

// Arithmetic
auto next_month = birthday + months{1};
auto next_year  = birthday + years{1};

// Validity check
year_month_day invalid{year{2025}, month{2}, day{30}};
invalid.ok();  // false — February doesn't have 30 days

// Last day of month
auto last = year_month_day_last{year{2025}, month_day_last{February}};
std::println("last day of Feb 2025: {}", (unsigned)last.day());  // 28

// Day of week
weekday wd{today};
wd.iso_encoding();  // 1=Monday, 7=Sunday

// Convert to time_point
auto tp = sys_days{birthday};  // sys_days = time_point<system_clock, days>

Time Zones (C++20)

cpp
#include <chrono>
using namespace std::chrono;

// Current time in a time zone
const auto* ny = locate_zone("America/New_York");
zoned_time ny_time{ny, system_clock::now()};
std::println("{}", ny_time);  // 2025-01-15 09:30:00 EST

// Convert between zones
const auto* tokyo = locate_zone("Asia/Tokyo");
zoned_time tokyo_time{tokyo, ny_time};
std::println("Tokyo: {}", tokyo_time);

// List all zones
for (const auto& info : get_tzdb().zones)
    std::println("{}", info.name());

// UTC offset
auto offset = ny_time.get_info().offset;  // std::chrono::seconds

Common Patterns

cpp
// Sleep
std::this_thread::sleep_for(100ms);
std::this_thread::sleep_until(std::chrono::steady_clock::now() + 1s);

// Timeout check
auto deadline = std::chrono::steady_clock::now() + 5s;
while (!done()) {
    if (std::chrono::steady_clock::now() > deadline)
        throw std::runtime_error("timeout");
    do_some_work();
}

// Unix timestamp
auto now = std::chrono::system_clock::now();
auto unix_ts = std::chrono::duration_cast<std::chrono::seconds>(
    now.time_since_epoch()).count();
std::println("Unix timestamp: {}", unix_ts);

// Parse from string (C++20)
std::chrono::sys_seconds tp;
std::istringstream ss{"2025-01-15 14:30:00"};
ss >> std::chrono::parse("%Y-%m-%d %H:%M:%S", tp);
Edit on GitHub