Module 28: C++ Date and TimeAdvanced40 min read
C++ <chrono> Library: Clocks, Durations & Benchmarking
Measure elapsed time accurately with std::chrono::steady_clock, durations, time_points, and format calendar dates with <ctime> / strftime.
Key Takeaways & Core Concepts
- `std::chrono::steady_clock`: Monotonic clock (never adjusts backward)—use for benchmarking and timeouts.
- `std::chrono::system_clock`: Wall-clock calendar time; converts to
std::time_tfor formatting withstd::localtime/std::strftime. - `std::chrono::high_resolution_clock`: Shortest tick period available.
1. `<chrono>` Clocks, Durations & Time Points
- `std::chrono::steady_clock`: Monotonic clock (never adjusts backward)—use for benchmarking and timeouts.
- `std::chrono::system_clock`: Wall-clock calendar time; converts to
std::time_tfor formatting withstd::localtime/std::strftime. - `std::chrono::high_resolution_clock`: Shortest tick period available.
1. Benchmarking & Chrono Duration Literals
1#include <iostream>
2#include <chrono>
3
4int main() {
5 using namespace std::chrono;
6 auto t0 = steady_clock::now();
7 volatile long long s = 0;
8 for (int i = 0; i < 100000; ++i) s += i;
9 auto elapsed = duration_cast<microseconds>(steady_clock::now() - t0);
10 std::cout << "Elapsed: " << elapsed.count() << " us\n";
11 return 0;
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: Measures elapsed microseconds monotonically using `steady_clock`.
2. Duration Literals (C++14)
using namespace std::chrono_literals; enables 100ms, 5s, 2h cleanly.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)