Search code examples
pythonpython-asyncio

Why does this asyncio program take longer than expected to run?


I have a program where I expect it to finish running in 8 secs but it takes 14 secs to run.

import asyncio
import time

async def gen1():
    yield b'1a1a'
    yield b'2b2b'

async def gen2():
    yield b'3c3c'
    yield b'4d4d'

async def sometask(file, offset, sleep1, sleep2, gen):
    await asyncio.sleep(sleep1)
    async for blok in gen():
        file.seek(offset)
        file.write(blok)
        offset = file.tell()
        await asyncio.sleep(sleep2)

async def main():
    with open('file', 'wb+') as f:
        await asyncio.gather(
            sometask(f, 0, 2, 6, gen1),
            sometask(f, 8, 0, 4, gen2))

start = time.perf_counter()

asyncio.run(main())

print(time.perf_counter()-start, 's')

The asyncio.gather actually runs in 8 secs (I think) but the program takes 14 secs to completely exit.


Solution

  • One of your task is sometask(f, 0, 2, 6, gen1), so:

    • you will wait first 2 seconds (sleep1)
    • gen1() will produce 2 values, so you will sleep 2 x 6 seconds (sleep2)
    • that is total 14 seconds.