I want time points picked in the same running thread to never be equal. That's because I use time points to differentiate between different calculation results.
Pseudocode:
StampedResult fn() {
auto result = Calculations();
auto time_stamp = std::chrono::steady_clock::now();
return {time_stamp, result);
}
Now, if Calculations()
was always complex, that would be auto-solved. But sometimes, Calculations()
may return immediately.
So, I thought I should check if 2 sequential calls to steady_clock::now()
can return the same value, like this:
https://onlinegdb.com/BkiDAZRe8
On onlinegdb.com
and on my laptop Intel® Core™ i7-8750H CPU @ 2.20GHz
I never get the same value returned. But could some other super-high frequency processor actually return the same values given steady_clock
's nanosecond accuracy?
Is it ensured that 2 sequential std::chrono::steady_clock::now() will not be equal?
It is not guaranteed by the standard. Quote from latest draft:
[time.clock.steady]
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.
Staying the same satisfies "never decrease" requirement.
Clocks have limited granularity and if the granularity is less than frequency of calls to now
, then it is feasible in theory that the value remains same between two calls. Complexity of the call is a practical limitation for the same value occurring again, but that is incidental.
If you wish to avoid duplicate value, then you can feasibly protect against the possibility by storing the last time stamp. If the new one is equal or less than the old, then nudge the new one up by one unit of measurement. The "less" part becomes possibility in case there are three equal values and second one was therefore nudged beyond the third.
steady_clock
is required to not go backwards, and it is required to progress forwards at regular intervals. That's it. It isn't even required to have nanosecond accuracy (or for the clock's actual accuracy to match the precision of its time points).
For what you're doing, making your own internal counter that goes up every time you do a calculation is a better alternative.
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