Home > Enterprise >  What precision is used by std::chrono::system_clock?
What precision is used by std::chrono::system_clock?

Time:09-08

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?

CodePudding user response:

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

CodePudding user response:

Is it possible that this will return e.g. microseconds with another compiler, operating system or hardware?

Yes, but you can always std::chrono::duration_cast it into a known duration unit. If you want it in seconds for example:

auto dur = std::chrono::duration_cast<std::chrono::seconds>(
               std::chrono::system_clock::now().time_since_epoch());

std::cout << dur << '\n';

Possible output:

1662575635s

Pre C 20:

std::cout << dur.count() << '\n';
1662575635

Note: Stay within the chrono domain until it's absolutely necessary to leave it (using .count() etc).

  • Related