TIL: asyncio.gather() Runs Coroutines Concurrently, Not Sequentially
While working with asynchronous code in Python, I stumbled upon a crucial distinction between using await sequentially and utilizing asyncio.gather(). The key difference lies in how coroutines are executed: sequentially or concurrently.
To illustrate this, consider a simple example where we have two asynchronous functions, async_func1 and async_func2, each simulating a 2-second delay. When using await sequentially, the total execution time would be approximately 4 seconds.
import asyncio
import time
async def async_func1():
await asyncio.sleep(2)
return "Func1 done"
async def async_func2():
await asyncio.sleep(2)
return "Func2 done"
async def main():
start_time = time.time()
await async_func1()
await async_func2()
print(f"Sequential execution time: {time.time() - start_time} seconds")
asyncio.run(main())
In contrast, using asyncio.gather() allows both functions to run concurrently, resulting in a total execution time of approximately 2 seconds. The asyncio.gather() function enables the execution of multiple coroutines at the same time, significantly improving performance in I/O-bound applications.
Takeaway: Using asyncio.gather() to run coroutines concurrently can drastically reduce overall execution time compared to sequential await statements.
Follow me on Dev.to for daily Python tips and quick guides!
🛠️ Recommended Tool
If you found this useful, check out Content Creator Ultimate Bundle (Save 33%) — $29.99 and designed for developers like you.
Get instant access to our best-selling AI Dev Boost, HTML Landing Page Templates, AI Prompts for Developers, and Python Automation Scripts Pack, perfect for content creators and marketers looking to elevate their game. This bundle is a must-have for anyone looking to create stunning content, build high-converting landing pages, and drive real results. With these tools, you'll be able to create engaging content, build beautiful landing pages, and boost your online presence.
Top comments (0)