Search code examples
c++c++-chrono

How can I know my `std::chrono::high_resolution_clock` correspond to the alias of `steady_clock` or `system_clock`, or other?


How can I know my std::chrono::high_resolution_clock correspond to the alias of steady_clock or system_clock, or other?

Many websites and books are providing examples using the system_clock, that might be goes back due to the synchronization, to measure the time spent for a function. I don't think that is the good idea to measure the time. Instead, I think we should use std::chrono::steady_clock.

Sometimes std::chrono::high_resolution_clock is used. According to the URL https://en.cppreference.com/w/cpp/chrono/high_resolution_clock , it says "It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock."

So, I want to know how can I check which aliases my std::chrono::high_resolution_clock correspond to. Any ideas?


Solution

  • Directly from Sam Varshavchik's comment. You can use std::is_same from <type_traits> to check if two types are the same.

    Here's an example for checking the three standard clocks in chrono:

    #include <chrono>
    #include <iostream>
    #include <type_traits>
    
    int main() {
        using namespace std::chrono;
    
        std::cout << std::boolalpha
            << std::is_same_v<system_clock, high_resolution_clock> << '\n'
            << std::is_same_v<system_clock, steady_clock> << '\n'
            << std::is_same_v<high_resolution_clock, steady_clock> << '\n'
        ;
    }
    

    Demo