asyncio.sleep() vs time.sleep() in Python

You aren’t seeing anything special because there’s nothing much asynchronous work in your code. However, the main difference is that time.sleep(5) is blocking, and asyncio.sleep(5) is non-blocking.

When time.sleep(5) is called, it will block the entire execution of the script and it will be put on hold, just frozen, doing nothing. But when you call await asyncio.sleep(5), it will ask the event loop to run something else while your await statement finishes its execution.

Here’s an improved example.

import asyncio

async def hello():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

async def main():
    await asyncio.gather(hello(), hello())

asyncio.run(main())

Will output:

~$ python3.7 async.py
Hello ...
Hello ...
... World!
... World!

You can see that await asyncio.sleep(1) is not blocking the execution of the script.

In contrast, replacing the line await asyncio.sleep(1) with time.sleep(1), the output will be

Hello ...
... World!
Hello ...
... World!

because time.sleep is blocking and the first call of hello() has to finish first before the second call of hello() starts running.

Hope it helps 🙂

Leave a Comment