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.
Are you?
clock_gettimeis required to return a time in nanoseconds, regardless of what clock you're accessing. This doesn't mean thatCLOCK_REALTIMEactually 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::periodis 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_gettimereally does provide better resolution (rather than simply giving more digits), you can just use that. In C++20,system_clockis explicitly UNIX time. As such, if you have a time in nanoseconds, you can convert it to atime_point<system_clock, nanoseconds>: