[Python-Dev] PEP 418: Add monotonic clock

Nick Coghlan ncoghlan at gmail.com
Wed Mar 28 16:17:32 CEST 2012


On Wed, Mar 28, 2012 at 8:56 PM, Victor Stinner
<victor.stinner at gmail.com> wrote:
>>>> In that case, I don't think time.try_monotonic() is really needed
>>>> because we can emulate "time.monotonic()" in software if the platform is
>>>> deficient.
>>>
>>> As I wrote, I don't think that Python should workaround OS bugs. If
>>> the OS monotonic clock is not monotonic, the OS should be fixed.
>>
>> I sympathize with this, but if the idea is that the Python stdlib should
>> use time.monotonic() for scheduling, then it needs to always be
>> available. Otherwise, we are not going to use it ourselves, and what
>> sort of example is that to set?
>
> There is time.hires() if you need a monotonic clock with a fallback to
> the system clock.

Completely unintuitive and unnecessary. With the GIL taking care of
synchronisation issues, we can easily coerce time.time() into being a
monotonic clock by the simple expedient of saving the last returned
value:

  def _make_monotic:
      try:
          # Use underlying system monotonic clock if we can
          return _monotonic
      except NameError:
          _tick = time()
          def monotic():
              _new_tick = time()
              if _new_tick > _tick:
                  _tick = _new_tick
              return _tick

  monotonic = _make_monotonic()

Monotonicity of the result is thus ensured, even when using
time.time() as a fallback.

If using the system monotonic clock to get greater precision is
acceptable for an application, then forcing monotonicity shouldn't be
a problem either.

Regards,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list