Help to understand asyncio.
There is a code:
import nest_asyncio
nest_asyncio.apply()
import time
import asyncio


async def f(n):
    await asyncio.sleep(1)
    for i in range(5000):
        i ** i
    return i


async def asynchronous():
    start=time.time()
    tasks=[asyncio.create_task(f(1)), asyncio.create_task(f(2)), asyncio.create_task(f(3))]
    result=await asyncio.gather(* tasks)
    print("Process took: {: .2f} seconds" .format(time.time() - start))
    return result

asyncio.run(asynchronous());


Runtime ~ 4 sec.One second per slip + one for each cycle.(Instead of 1-2 seconds in asynchronous operation)
Why the code does not run asynchronously?

1 Answers 1

Asynchrony is built on cooperative multitasking so that it is effective, it is necessary that coroutines give up control on blocking calls.And the loop inside f is not blocked and does not give up control.Therefore, if the execution of one cycle run takes a second, then three runs will require three seconds.
  • But unless I write"await asyncio.sleep(1)", I don’t give control?
    I understand that the cycle is blocking, but I do not understand why, how to proceed to the next function
    – Frisky72 Jul 27 '19 at 15:03
  • Frisky72, yes, it is given.If you did not give up, the total execution time would be two seconds longer.To see the difference, try instead of one second call of sleep at the beginning of the coroutine to slow down for 5 milliseconds each iteration:

    async def f(n):
        for i in range(500):
            await asyncio.sleep(5e-3)
            i ** i
        return i

    and then the same thing, but without returning control to the event loop

    async def f(n):
        for i in range(500):
            time.sleep(5e-3)
            i ** i
        return i
    – Ashamed Anteater Jul 27 '19 at 15:09
  • Ashamed Anteater, it means that sleep does not affect this.
    To perform the f() function at the same time, we need other tools, asyncio is not about that?
    – Frisky72 Jul 27 '19 at 15:22
  • Frisky72, asyncio is reflected directly in its name - Asynchronous IO, that is, asynchronous I/O.To perform cpu bound tasks at the same time, streams are usually used, but not in Python.In Python, due to GIL, you have to use multiprocessing. – Ashamed Anteater Jul 27 '19 at 15:36
  • Ashamed Anteater, Thank you – Frisky72 Jul 27 '19 at 15:39