Time Events with std::chrono
Learn to implement time events with std::chrono.
We'll cover the following...
The std::chrono
library provides tools for measuring and reporting time and intervals. Many of these classes and functions were introduced with C++11. There have been significant changes and updates for C++20, but at the time of writing, many of those updates are not yet implemented.
Using the chrono
library, this recipe explores techniques for timing events.
How to do it
The system_clock
class is used for reporting the current date and time. The steady_clock
and high_resolution_clock
classes are used for timing events. Let's look at the differences between these clocks:
Because these names can be long and unwieldy, we'll use some type aliases throughout this recipe:
using std::chrono::system_clock;using std::chrono::steady_clock;using std::chrono::high_resolution_clock;using std::chrono::duration;using seconds = duration<double>;using milliseconds = duration<double, std::milli>;using microseconds = duration<double, std::micro>;using fps24 = duration<unsigned long, std::ratio<1, 24>>;
The duration
class represents an interval between two points in time. These aliases are convenient for using different intervals.
We can get the current time and date by using the
system_clock
class:
auto t = system_clock::now();cout << format("system_clock::now is {:%F %T}\n", t);
The system_clock::now()
function returns a time_point
object. The <chrono>
library includes a format()
specialization for time_point
that uses strftime()
format specifiers.
The output is:
system_clock::now is 2023-02-05 13:52:15
The <iomanip>
header includes put_time()
, which works like strftime()
for ostream
:
std::time_t now_t = system_clock::to_time_t(t);cout << "system_clock::now is " << std::put_time(std::localtime(&now_t), "%F %T") << '\n';
put_time
() takes a pointer to a C-style time_t*
value. system_clock::to_ time_t
converts a time_point
object to time_t
. This gives the same output as our ...