I decided not use asyncio.sleep()
and tried to create my own coroutine function as shown below. Since, time.sleep
is an IO bound function, I thought this will print 7 seconds. But it prints 11 seconds.
import time
import asyncio
async def my_sleep(delay):
time.sleep(delay)
async def main():
start = time.time()
await asyncio.gather(my_sleep(4), my_sleep(7))
print("Took", time.time()-start, "seconds")
asyncio.run(main())
# Expected: Took 7 seconds
# Got: Took 11.011508464813232 seconds
Though if I write a similar code with threads, It does print 7 seconds. Do Task
objects created by asyncio.gather
not recognize time.sleep
as an IO bound operation, the way threads do? Please explain why is it happening.