Search code examples
c++timec++-chronosystem-clock

What precision is used by std::chrono::system_clock?


Here's some code that I found:

std::cout << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;

This prints 1662563612364838407 for me; so it looks like this prints the number of nanoseconds since the UNIX epoch (1970-01-01).

But is this precision guaranteed? I didn't find any indication at https://en.cppreference.com/w/cpp/chrono/system_clock that this value will always be in nanoseconds. Is it possible that this will return e.g. microseconds with another compiler, operating system or hardware?


Solution

  • No it is not guaranteed. You can use the clocks period member alias to get tick period in seconds:

    #include <chrono>
    #include <iostream>
    
    int main() {
        std::cout << std::chrono::system_clock::period::num << " / " << std::chrono::system_clock::period::den;
    }
    

    Possible output:

    1 / 1000000000