The C++ standard library
C++11 introduced the library, a library for handling time and dates. It provides a rich set of tools for measuring time intervals, performing time-point calculations, and handling dates and times. library is the core part of the C++ standard library for time-related operations.
Basic concepts
Time Points
A time point represents a specific point in time, usually associated with a particular clock.
Durations
A duration represents the time interval between two time points.
Clocks
A clock is the source of time points and durations. C++ provides several different clocks, such as the system clock and high-resolution clock.
Basic Syntax
Including the header
When using Before using the library, you need to include the corresponding header:
#include
Using time points
auto now = std::chrono::system_clock::now();
Using durations
auto duration = std::chrono::seconds(5);
Computing time points
auto future_time = now + duration;
Example
Measuring function execution time
Below is an example using library to measure function execution time:
Example
#include
#include
void
someFunction
(
)
{
// Simulate some operations
std
::
this_thread
::
sleep_for
(
std
::
chrono
::
seconds
(
1
)
)
;
}
int
main
(
)
{
auto
start
=
std
::
chrono
::
high_resolution_clock
::
now
(
)
;
someFunction
(
)
;
auto
end
=
std
::
chrono
::
high_resolution_clock
::
now
(
)
;
auto
duration
=
std
::
chrono
::
duration_cast
<
std
::
chrono
::
milliseconds
(
end
start
)
;
std
::
cout
<<
"Function took "
<<
duration.
count
(
)
<<
" milliseconds to execute."
<<
std
::
endl
;
return
0
;
}
Output result:
Function took 1000 milliseconds to execute.
Handling dates and times
library can also be used to handle dates and times. Below is an example using std::chrono::system_clock and std::chrono::time_point to get the current date and time:
Example
#include
#include
#include
int
main
(
)
{
auto
now
=
std
::
chrono
::
system_clock
::
now
(
)
;
std
::
time_t
now_c
=
std
::
chrono
::
system_clock
::
to_time_t
(
now
)
;
std
::
cout
<<
"Current date and time: "
<<
std
::
ctime
(
&
now_c
)
;
return
0
;
}
Output result:
Current date and time: Fri Mar 11 12:34:56 2022
Advanced usage
Using different clocks
C++ provides several clocks, for example:
std::chrono::system_clock: System clock, usually synchronized with the system time.std::chrono::steady_clock: Monotonic clock, not affected by system time changes.std::chrono::high_resolution_clock: Provides the highest-resolution clock.
Formatting dates and times
You can use the and to format dates and times:
Example
#include
#include
#include
#include
int
main
(
)
{
auto
now
=
std
::
chrono
::
system_clock
::
now
(
)
;
std
::
time_t
now_c
=
std
::
chrono
::
system_clock
::
to_time_t
(
now
)
;
std
::
cout
<<
std
::
put_time
(
std
::
localtime
(
&
now_c
)
,
"%Y-%m-%d %H:%M:%S"
)
;
return
0
;
}
Output result:
2022-03-11 12:34:56