Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ensured that 2 sequential std::chrono::steady_clock::now() will not be equal?

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?

like image 379
Bill Kotsias Avatar asked Dec 10 '22 01:12

Bill Kotsias


2 Answers

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.

like image 69
eerorika Avatar answered Apr 29 '23 06:04

eerorika


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.

like image 27
Nicol Bolas Avatar answered Apr 29 '23 05:04

Nicol Bolas