Sobes.tech
Middle

Look at the code with asyncio. How long will the main function take to execute? How can you make the coroutines run in parallel?

sobes.tech AI

Answer from AI

It is difficult to say exactly without specific code, but usually if coroutines are called sequentially using await, the total execution time is equal to the sum of the times of all coroutines.

To run coroutines in parallel, asyncio.gather or creating tasks via asyncio.create_task are used.

Example:

import asyncio

async def task(id, delay):
    await asyncio.sleep(delay)
    print(f"Task {id} done")

async def main():
    # Sequential execution
    await task(1, 2)
    await task(2, 2)

asyncio.run(main())

# To run in parallel:
async def main_parallel():
    await asyncio.gather(
        task(1, 2),
        task(2, 2)
    )

asyncio.run(main_parallel())

In the first case, the total time is about 4 seconds, in the second — about 2 seconds, since the tasks are executed simultaneously.