C++ Standard Library<chrono>
Introduced in C++11<chrono>The library is used 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.<chrono>The library is a core part of the C++ standard library for handling time-related operations.
Basic concepts
Time Points
A time point represents a specific point in time, usually associated with a particular clock.
Durations
Duration represents the time interval between two time points.
Clocks
Clocks are the source of time points and durations. C++ provides several different clocks, such as the system clock, high-resolution clock, and others.
Basic Syntax
Include Header Files
When using<chrono>Before using the library, you need to include the corresponding header file:
#include <chrono>
Using Time Points
auto now = std::chrono::system_clock::now();
Using durations
auto duration = std::chrono::seconds(5);
Calculating Time Points
auto future_time = now + duration;
Example
Measuring function execution time
Below is an example using<chrono>A simple example of the library measuring function execution time:
Example
#include <chrono>
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
<chrono>The library can also be used to handle dates and times. Below is an example usingstd::chrono::system_clockandstd::chrono::time_pointExample of getting the current date and time:
Example
#include <chrono>
#include <ctime>
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 multiple clocks, for example:
std::chrono::system_clock: System clock, usually synchronized with system time.std::chrono::steady_clock: Monotonic clock, unaffected by changes to system time.std::chrono::high_resolution_clock: Provides the clock with the highest resolution.
Formatting date and time
You can use<iomanip>and<ctime>to format date and time:
Example
#include <iomanip>
#include <chrono>
#include <ctime>
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:56other extensions