Welcome to this comprehensive guide on the std::system_clock in C++! We'll explore how to work with time using this powerful tool, making your programs more dynamic and practical.
std::system_clock šstd::system_clock is a C++ standard library class that deals with the system's real-time clock. It provides the current time measured in seconds since a specific point in time, called the epoch.
First, let's see how to use std::system_clock to get the current time.
#include <iostream>
#include <chrono>
int main() {
auto now = std::chrono::system_clock::now();
std::cout << "Current time (since epoch): " << std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count() << std::endl;
return 0;
}This code gets the current time in seconds since the epoch and prints it out. Let's break it down:
#include <iostream> is needed for console input/output#include <chrono> is the C++ header for time-related functionalitystd::chrono::system_clock::now() gets the current time as a std::chrono::time_point objectstd::chrono::duration_cast<std::chrono::seconds>(...) converts the time point to secondsstd::chrono::seconds::count() returns the number of seconds since the epochstd::cout prints the resultstd::chrono::duration and std::chrono::time_point are key components to manipulate time in C++. Let's see a simple example:
#include <iostream>
#include <chrono>
int main() {
auto start = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(5));
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(end - start);
std::cout << "Slept for: " << elapsed.count() << " seconds" << std::endl;
return 0;
}In this example, we:
startstd::this_thread::sleep_for(std::chrono::seconds(5)) to sleep for 5 secondsend after sleepingelapsed as the difference between end and startWhat does the `std::chrono::duration_cast` function do?
Now, let's see how to measure the time taken to execute a piece of code:
#include <iostream>
#include <chrono>
void my_function() {
// Your code here
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
my_function();
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << "Function execution time: " << elapsed << " microseconds" << std::endl;
return 0;
}In this example, we use std::chrono::high_resolution_clock for higher precision:
start before calling the functionmy_function()end after the function finisheselapsed in microsecondsThat's it for this lesson! With std::system_clock, you can now make your programs more dynamic and practical by working with time. In the next lesson, we'll explore more advanced features of C++ time-related functionality.
Stay tuned and happy coding! šš»š”š