Chrono Library in Modern C++

Hello, everyone. In this article, we are going to briefly talk about the Chrono library in the standard template library.

First of all, in order to use the Chrono library, we first need to include the header chrono to our code. This header includes all the main methods related to time.

#include <chrono>

In general, there are two important concepts related to the Chrono library: clock and duration. You can easily guess that the clock represents the time point and the duration represents the time interval:

Clock:
1. std::chorono::system_clock — represents the system-wide real-time wall clock. (not steady because for most of the systems, user can adjust the time anytime, so system_clock is not monotonic).
2. std::chorono::steady_clock — goes at a uniform rate (monotonic).
3. std::chorono::high_resolution_clock — provides smallest possible tick period.

Duration:
std::chrono::duration<class rep, class period = std::ratio<1>>: represents time duration. The first parameter defines the data type we want to save our time, the second parameter defines the ratio for current time. For example:
duration<int, ratio<1, 1>>:  //number of seconds stored in a int
duration<double, ratio<60,1>>  //number of minutes stored in a double

std::chrono::system_clock::duration is shortcut of std::chrono::duration<T, system clock::period>. By default, the std::chrono::system_clock::duration is equivalent to std::chrono::duration<long long, std::ratio_multiply<std::hecto, std::nano>>.

std::chrono::time_point<>: represents a point of time.

std::chrono::time_point<system_clock, millisecond>: according to system_clock, the elapsed time since epoch in milliseconds. (00:00 January 1st, 1970 (coordinated Universal Time – UTC) – the epoch of a clock)

We can also use some built-in predefined time units: nanoseconds, microseconds, milliseconds, seconds, minutes, hours…

system_clock::time_point is a shortcut of time_point <system_clock, system_clock::duration>;  steady_clock::time_point is a shortcut of time_point <steady_clock, steady_clock::duration>

The following code provides some reference for how to use the chorono library. You can check the comment and get the idea:

That’s all for how to use the chorono library. Please give it a try and see what you can get.  Thank you for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s