chrono
chrono
chrono (since C++11)
Prerequisites
1. What is <chrono>?
<chrono> is the C++ standard library for time measurement and manipulation.
It provides:
- Clocks → get current time
- Durations → represent time intervals
- Time points → represent a point in time
Designed to be type-safe and precise
Use it when:
- measuring execution time
- handling time durations
- implementing timers or delays
- writing performance-critical code
Duration
Represents a time interval
1
std::chrono::duration<Rep, Period>
Rep→ numeric type (e.g.,int,double)Period→ time unit (ratio)
1
2
3
4
std::chrono::seconds
std::chrono::milliseconds
std::chrono::microseconds
std::chrono::nanoseconds
Time Point
Represents a specific point in time
1
std::chrono::time_point<Clock>
Always associated with a clock
Clock
Provides the current time
Types of Clocks
1
2
3
std::chrono::system_clock
std::chrono::steady_clock
std::chrono::high_resolution_clock
2. How to use
✔️ Measuring Execution Time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <chrono>
int main()
{
auto start = std::chrono::high_resolution_clock::now();
// code to measure
for (int i = 0; i < 1000000; ++i)
{
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = end - start;
std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
}
✔️ Create Duration
1
2
std::chrono::seconds s(5);
std::chrono::milliseconds ms(1500);
✔️ Arithmetic
1
auto total = s + std::chrono::seconds(3); // 8 seconds
✔️ Conversion
1
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(s);
✔️ Access Value
1
ms.count(); // returns numeric value
2-1. Clocks Explained
system_clock
- Represents real-world wall clock time
- Can be adjusted (NTP, user changes)
Use for:
- timestamps
- logging
steady_clock
- Monotonic (never goes backward)
- Not affected by system time changes
Use for:
- measuring durations
- performance timing
high_resolution_clock
- Highest available precision
- Often alias of one of the above
Use when you need maximum precision
| Clock | Stable | Affected by System Time | Use Case |
|---|---|---|---|
| system_clock | ❌ | ✅ | real-world time |
| steady_clock | ✅ | ❌ | benchmarking |
| high_resolution_clock | depends | depends | high precision |
2-2. Sleep
1
2
3
4
#include <thread>
std::this_thread::sleep_for(std::chrono::seconds(1));
std::this_thread::sleep_until(std::chrono::steady_clock::now() + std::chrono::seconds(1));
2-3. Getting Current Time
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
std::cout << std::ctime(&time);
}
This post is licensed under CC BY 4.0 by the author.