3

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?

oliver
  • 6,204
  • 9
  • 46
  • 50
  • it's unclear. `std::chrono::high_resolution_clock` also doesn't have defined precision, because nothing can be counted faster than the system tick. For example on a small embedded MCU it can be microseconds – phuclv Sep 07 '22 at 15:37
  • https://en.cppreference.com/w/cpp/chrono/system_clock – Jesper Juhl Sep 07 '22 at 15:52

2 Answers2

5

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
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

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).

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108