Time with std::chrono in C++
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.
Durations carry units
std::chrono::milliseconds{1500} + std::chrono::seconds{2} is type-checked arithmetic — mixing units safely, no magic 1000s.
steady for intervals
auto t0 = steady_clock::now(); ...; auto dt = steady_clock::now() - t0; — monotonic benchmarking immune to clock adjustments.
system for wall time
system_clock::now() converts to time_t for timestamps and logs — the human-facing clock, adjustments and all.
Sleep and wait properly
std::this_thread::sleep_for(50ms) pauses cleanly with duration literals (using namespace std::chrono_literals).
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.