Aleksandr Gavrilov
Aleksandr Gavrilov

Reputation: 193

Why asyncio.sleep doesn't work in python?

Here is my code:

logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s %(message)s',
                    level=logging.INFO,
                    handlers=[
                        logging.FileHandler("bot.log"),
                        logging.StreamHandler()
                    ]
                    )
...

async def _create_order(order, delay=0):
    if delay:
        logging.info(f'sleep {delay}')
        start = timeit.default_timer()
        await asyncio.sleep(delay)
    logging.info(f'elapsed {timeit.default_timer() - start}')
    ...

And result in log:

2021-04-05 17:20:18,274 root INFO sleep 0.01
2021-04-05 17:20:18,274 root INFO elapsed 0.0001959000000000266

With delay = 0.1 it works better, but not as expected:

2021-04-05 17:25:50,849 root INFO sleep 0.1
2021-04-05 17:25:50,940 root INFO elapsed 0.09012620000000027

Why asyncio.sleep doesn't work? OS Windows 10. Python 3.9

Upvotes: 1

Views: 743

Answers (2)

Matt_De
Matt_De

Reputation: 11

This is apparently a known issue with asyncio on Windows, and is related to the poor resolution of the system calls Windows provides to get the state of the internal clock, around 15 ms of error. You can test if this is the issue you're experiencing by running,

>>> import time; print(time.get_clock_info('monotonic'))

which returns among other things the resolution of the clock.

Upvotes: 1

user2357112
user2357112

Reputation: 280887

asyncio's sleep resolution is pretty bad, especially on Windows. On Windows, the resolution is about 15 milliseconds. Your first sleep duration is lower than the sleep resolution, so it can end up not really sleeping at all. With the second test, the difference between the requested and actual sleep duration is still less than 15 milliseconds.

Upvotes: 2

Related Questions