Is there a Rust equivalent of C++'s std::chrono::steady_clock? (emphasis on steady)
The time points of this clock cannot decrease as physical time moves forward and the time between ticks of this clock is constant.
std::time::Instant apparently doesn't fit:
... instants are not guaranteed to be steady. In other words, each tick of the underlying clock might not be the same length (e.g. some seconds may be longer than others). An instant may jump forwards or experience time dilation (slow down or speed up) ...
Here are few facts that I've gathered:
I didn't check other platforms, but since Rust uses llvm under the hood, it is likely it utilizes the same syscalls. So Rust's Interval and C++ steady_clock implementations use the exact same syscalls, at least for gcc and llvm.
Moreover the Unix's clock_gettime() syscall is not guaranteed to have a steady rate (or at least I couldn't find such guarantee), and so such C++ guarantee is puzzling. Furthermore if we look at the actual C++ standard, it says something a bit different:
23.17.7.2 Class steady_clock
- Objects of class steady_clock represent clocks for which values of time_point never decrease as physical time advances and for which values of time_point advance at a steady rate relative to real time. That is, the clock may not be adjusted.
For me it sounds like "steady rate" is more about "the clock cannot be adjusted" rather than a guarantee that the time between ticks is constant. This term "steady rate" sounds fuzzy for me. But, I suppose it is a matter of interpretation.
Either way, both Rust and C++ implement these clocks in the same way, and that is unlikely to change. I suppose that the truth is somewhere in between: C++'s guarantee is impossible to be true (unless the time is constant up to some precision), while Rust's warning is probably not as bad as it sounds.
EDIT: some x86 cpus, in fact all Intel cpus starting with Pentium 4, have this feature called "constant TSC". According to the wikipedia it can be accessed through clock_gettime(CLOCK_MONOTONIC_RAW, ...) on Unix systems, and it is built into QueryPerformanceCounter on Windows. This "clock" ticks at cpu speed independent way, but how close it is to "constant rate" is not clear (at least for me). Probably quite close. Of course you'd need to do a direct syscall on Unix, and it is limited to x86 arch only. Also does not seem to tick while the system is suspended. I don't know if other archs have similar thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With