Measuring time using chrono

suggest change

std::chrono::steady_clock measures elapsed time. system_clock tracks wall-clock time and can jump when the system time is adjusted, so it is a poor choice for a duration.

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    auto start = std::chrono::steady_clock::now(); // time_point of steady_clock
    { // The code to test
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    auto end = std::chrono::steady_clock::now();

    std::chrono::duration<double> elapsed = end - start;
    std::cout << "Elapsed time: " << elapsed.count() << "s";
}

In this example, sleep_for was used to make the active thread sleep for a time period measured in std::chrono::seconds, but the code between braces could be any function call that takes some time to execute.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents