0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Not enough to explain a large discrepancy, but you could also switch to an async file libaray. Not sure if this is outdated, but its interesting: https://stackoverflow.com/questions/34699948/does-asyncio-supports-asynchronous-i-o-for-file-operations – tdelaney Aug 24 '23 at 21:11
  • Welcome to SO! For debugging questions in the future, please make a [mre]. That can help to catch basic mistakes like this. I was able to get it down to [this](//gist.github.com/wjandrea/45d16e0eb20ebe102ad5130d4279936d). For more tips, check out [ask]. – wjandrea Aug 24 '23 at 21:20

1 Answers1

4

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.
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91