Durations and Clocks
Measure time intervals.
Why <chrono>?
The <chrono> library gives C++ a type-safe way to work with time. Instead of raw integers, you use strongly typed durations and time points so the compiler catches unit mistakes.
- No more mixing up seconds and milliseconds.
- Units are part of the type system.
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
seconds s{5};
std::cout << "Duration: " << s.count() << " seconds\n";
return 0;
}What Is a Duration?
A std::chrono::duration represents a span of time. It stores a count of ticks plus a ratio describing the tick period. Predefined aliases cover common units.
hours,minutes,secondsmilliseconds,microseconds,nanoseconds
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
milliseconds ms{1500};
std::cout << ms.count() << " ms\n";
return 0;
}All lessons in this course
- Durations and Clocks
- Time Points
- Measuring Code Performance
- Calendar and Time Zones