std::chrono::system_clock::time_since_epoch().count() gives me a result in microseconds.
I want the current time in nanoseconds. But I can't use high_resolution_clock because on my system it is an alias on steady_clock (the monotonic clock).
I know my system is nanoseconds capable, because if I use clock_gettime(CLOCK_REALTIME, &ts) I am getting a correct nanosecond-resolution epoch time.
How can I tell std::chrono to use the nanosecond resolution? I'd like to avoid using clock_gettime and stick to the cpp wrapper.
I am getting a correct nanosecond-resolution epoch time.
Are you? clock_gettime
is required to return a time in nanoseconds, regardless of what clock you're accessing. This doesn't mean that CLOCK_REALTIME
actually provides this resolution. It may internally only have microsecond resolution and expresses nanoseconds by multiplying by 1000.
By contrast, the actual resolution of a chrono clock is specified by the implementation. It is not a mandated part of the UI; it can vary from system to system and from clock to clock. So if a particular implementation's system_clock::period
is in microseconds, then that is all the resolution the implementation is willing to claim to provide.
Maybe the implementation could provide more resolution, but if it could, it would probably say so. So if it doesn't, then that means the implementation doesn't feel comfortable claiming to provide more resolution.
However, if you feel that clock_gettime
really does provide better resolution (rather than simply giving more digits), you can just use that. In C++20, system_clock
is explicitly UNIX time. As such, if you have a time in nanoseconds, you can convert it to a time_point<system_clock, nanoseconds>
:
namespace chrono = std::chrono;
...
using nano_sys = chrono::time_point<chrono::system_clock, chrono::nanoseconds>;
auto sys_tp_ns = nano_sys(chrono::nanoseconds(time_in_nanoseconds));