How do I use std::chrono::steady_clock vs system_clock in C++?

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.

std::chrono::steady_clock

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.

std::chrono::system_clock

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.

Example


#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;
}
    

C++ std::chrono steady_clock system_clock time measurement performance metric