Welcome to our comprehensive guide on std::chrono in C++! This powerful library was introduced in C++11, providing a unified way to represent and manipulate time durations and points in time. Let's dive in and learn how to measure and control time in your C++ programs.
std::chronostd::chrono is a header-only C++11 library that provides a rich set of types for dealing with time. The main goal is to create a uniform and flexible approach to time measurement and manipulation.
š Note: To use std::chrono, you need to include the <chrono> header in your C++ source file.
std::chrono Typesstd::chrono::time_pointA time_point represents a specific moment in time. You can think of it as a timestamp.
#include <iostream>
#include <chrono>
int main() {
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::cout << "Current time: " << std::put_time(now.date_time.get_system_time(), "%Y-%m-%d %H:%M:%S") << std::endl;
return 0;
}std::chrono::durationA duration represents a time interval. It can be used to measure the elapsed time between two events.
To measure the elapsed time between two events, you can use std::chrono::duration_cast.
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
auto start = high_resolution_clock::now();
for (size_t i = 0; i < 1000000; ++i) {
// Your code here
}
auto end = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(end - start);
std::cout << "Elapsed time: " << duration.count() << " milliseconds." << std::endl;
return 0;
}What does `std::chrono::time_point` represent in a C++ program?
In this lesson, we covered the basics of the std::chrono library in C++, focusing on the key types time_point and duration. We explored how to use these types to represent specific moments in time and time intervals, respectively.
In the next lesson, we'll delve deeper into std::chrono, learning more about time units, high-resolution clocks, and advanced time manipulation techniques.
Stay tuned and happy coding! š