How to query Python event loop monotonic clock resolution

Viewed 300

Currently the asyncio event loop simply calls time.monotonic(), so we can easily query the resolution with time.get_clock_info('monotonic').resolution, but in case the asyncio implementation changes do we have a public API available for querying that new monotonic clock's resolution (i.e., can we query the resolution of asyncio.get_event_loop().time())?

2 Answers

The asyncio source in the standard library is part of a Python installation.

In the asyncio/base_events.py file there is an event loop base class. In its initialization function it saves the clock resolution for its internal use.

self._clock_resolution = time.get_clock_info('monotonic').resolution

and the mentioned usage is:

    # Handle 'later' callbacks that are ready.
    end_time = self.time() + self._clock_resolution
    while self._scheduled:
        handle = self._scheduled[0]
        if handle._when >= end_time:
            break

I could not find other uses in the 3.9.1 asyncio code.

The conclusion is that with a high probability there is no public API, but the clock resolution value can be obtained from the mentioned private attribute belonging to the event loop. As always, there is no guarantee when dealing with an undocumented private data.

I think it would be most practical to raise an Exception (perhaps with further direction) if there is insufficient accuracy.

import time
if time.get_clock_info('monotonic').resolution > accuracy_limit:
    raise OSError("monotonic timer is insufficiently accurate")

EDIT: ah, not quite; re-reading, the question is perhaps better how to detect if the asyncio implementation is not backed by time.monotonic()?

However, I suggest that such an implementation is unlikely as it seems needlessly bad (ie. it would be some fraction of a different monotonic clock than is provided to Python?..), and also that systems must provide a monotonic clock (detecting if the timer is really monotonic is left as an exercise to the reader)

Related