educative.io

Educative

Run async functions

In the Section “Concurrency using asyncio” we have the following code:

import asyncio
import time

async def func1():
  for i in range(5):
    print('Inside Func1')
   await asyncio.sleep(1)

 async def func2():
   for i in range(5):
     print('Inside Func2')
     await asyncio.sleep(0.8)

start = time.time()
async_tasks = asyncio.gather(func1(), func2())
asyncio.get_event_loop().run_until_complete(async_tasks)
end = time.time()
print('Asyncio took {} seconds'.format(round(end-start),2))

Running the code prints “Asyncio took 5 seconds”.
Why isn’t it 9 seconds (5x1 + 5x0.8) ?

Hello @rinkalaone,

Basically, when the Func1() will be executed he waits for 1 second and asks the event loop to execute the Func2(). Func2() will be executed and goes on a wait of 0.8 seconds that will be covered in the wait of 1 second of the Func1()'s wait because they share the same clock.

By that, the wait of 0.8 finishes first, and Func2() will be ready for execution again. As you can see in the output that after the execution of Func1(), Func2() was executed 2 times. In these switching the 4 seconds that are calculated by (5*0.8) will be covered in the 5 seconds that are calculated by (5*1) because they share the same clock.

I hope I have answered your query; please let me know if you still have any confusion.

Thank You :blush:

1 Like

Thank you @Abdul_Mateen!
Of course! Completly got it.