The Chrono Library
The <chrono>
library contains functions for handling time related things.
The code in these examples uses the C++20 language standard.
Clock Types
Use the system_clock
when you want to get the current calendar date and time.
Use the steady_clock
when you want to measure time elapsed.
This is likely suitable for many benchmarking needs.
Use the high_resolution_clock
for benchmarking and profiling. This may be the
same as the previous two, so it may be better to implement your own high
resolution clock using OS features. This guide will explain how to do this
for Windows and Linux.
Getting The Current Time
Using chrono we can check the current date and time.
|
|
This program will output something like this
|
|
Measuring Time
It is common to want to measure how much time something takes to run, like for example when benchmarking your code for performance.
For this purpose, we can use the steady_clock
to measure time elapsed like a stopwatch.
The Example
|
|
This program will output something like the following
|
|
Line By Line
We will first get the current time and then do some lengthy operation to see how long it takes.
|
|
We will just simulate something taking a long time with the sleep function.
The sleep function will try to sleep for some amount of time, but the actual amount of time is likely to vary due to system noise.
|
|
After the operation we will again obtain the current time.
|
|
We can then find the total time elapsed by subtracting the start and end times.
For example, if the start time is 9:30AM and the end time is 9:35AM then five minutes have gone by.
This line will get the elapsed time in seconds as a floating point number.
|
|
We can get a different resolution by assigning to a duration with a different ratio.
This line will get the time in milliseconds as a float.
|
|
We can get a different resolution with duration_cast
.
This line will get the time in microseconds as an integer.
|
|
The default resolution will be integer nanoseconds.
|
|
The .count()
function returns the int or float value of the duration.
A Timer Class
Here is an example time measurement class you can use.
This class provides a slightly nicer more convenience syntax for performance benchmarking your code.
|
|
Cover Photo
Credit: Max Shein