In C++, the std::chrono::steady_clock
and std::chrono::system_clock
are part of the chrono
library, and both serve different purposes when measuring time.
This clock is a monotonic clock that guarantees a steady increment of time. It is suitable for measuring intervals and durations because it is not affected by system time changes (e.g., the user adjusting the system clock). You should use steady_clock
when you need to measure how long events take, such as in performance measurements.
This clock represents the system-wide real time and can be converted to and from calendar time. It might be affected by system clock changes, such as adjustments for daylight savings. Use system_clock
when you need to perform operations involving actual time, such as timestamps.
#include <iostream>
#include <chrono>
#include <thread>
int main() {
// Using steady_clock
auto start_steady = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(2));
auto end_steady = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_steady = end_steady - start_steady;
std::cout << "Elapsed time using steady_clock: " << elapsed_steady.count() << " seconds\n";
// Using system_clock
auto start_system = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(2));
auto end_system = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_system = end_system - start_system;
std::cout << "Elapsed time using system_clock: " << elapsed_system.count() << " seconds\n";
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?