Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading