Learn C++
#include "advanced/chrono.hpp"

Time with std::chrono in C++

//concept

std::chrono (<chrono>) models time as durations (50ms), time_points (now + 50ms), and clocks that produce them — type-safe arithmetic where seconds + milliseconds just works and unit mistakes fail to compile. steady_clock measures intervals (monotonic, never adjusted); system_clock tracks wall time (adjustable, convertible to calendar); high_resolution_clock is typically steady_clock aliased.

C++20 calendars (year/month/day) and time zones complete the picture for human time. Benchmark with steady_clock around the code, subtract time_points for a duration, and cast units explicitly — never count() raw ticks across clock types.

//how it works
1

Durations carry units

std::chrono::milliseconds{1500} + std::chrono::seconds{2} is type-checked arithmetic — mixing units safely, no magic 1000s.

2

steady for intervals

auto t0 = steady_clock::now(); ...; auto dt = steady_clock::now() - t0; — monotonic benchmarking immune to clock adjustments.

3

system for wall time

system_clock::now() converts to time_t for timestamps and logs — the human-facing clock, adjustments and all.

4

Sleep and wait properly

std::this_thread::sleep_for(50ms) pauses cleanly with duration literals (using namespace std::chrono_literals).

//example
#include <iostream>
#include <chrono>
 
int main() {
using namespace std::chrono;
auto start = steady_clock::now();
volatile long acc = 0;
for (long i = 0; i < 1000000; ++i) acc += i;
auto took = duration_cast<milliseconds>(steady_clock::now() - start);
std::cout << took.count() << "ms" << std::endl;
return 0;
}
Output
3ms
1steady_clock stamps monotonic start time, immune to system clock changes mid-measurement.
2A million-iteration accumulation (volatile so it isn't optimized away) provides real work to time.
3duration_cast renders the interval as whole milliseconds — a small single-digit number on modern hardware.
//use cases
Benchmarking snippets with steady_clock snapshots around the code
Timeouts and rate limits expressed as typed durations
Log timestamps from system_clock converted to calendar time
C++20 calendar dates (year/month/day) for schedule logic

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.