Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await multiple async functions in python

Awaiting for multiple async functions is not really working asynchronously,for example,I am expecting below code to run in ~6 seconds, but it is running like synchronous code and executing in ~10 seconds. But when I tried it in asyncio.gather, it is executing in ~6 seconds.

Can someone explain why is this so?

 #Not working concurrently
 async def async_sleep(n):
    await asyncio.sleep(n+2)
    await asyncio.sleep(n)
start_time = time.time()
asyncio.run(async_sleep(4))
end_time = time.time()
print(end_time-start_time)
#Working concurrently 
async def async_sleep(n):
    await asyncio.gather(asyncio.sleep(n+2),
                    asyncio.sleep(n))
like image 868
Venkata Ram Avatar asked Oct 15 '22 12:10

Venkata Ram


1 Answers

Can someone explain why [gather is faster than consecutive awaits]?

That is by design: await x means "do not proceed with this coroutine until x is complete." If you place two awaits one after the other, they will naturally execute sequentially. If you want parallel execution, you need to create tasks and wait for them to finish, or use asyncio.gather which will do it for you.

like image 158
user4815162342 Avatar answered Oct 20 '22 16:10

user4815162342