0

I want to understand why async await didnt work while looping around a range, below is the code. Is it that the function I called is not asynchronous. Not able to understand it. Problem is same thing worked when I used non async process instead of for loop. Is there something i'm missing. Thanks

import asyncio
import time

async def test():
    response = {}
    s = time.time()
    tasks=[]
    answers=[]
    for k in range(4):
        print(k)
        tasks.append(asyncio.create_task(take_time()))
    answers = await asyncio.gather(*tasks)
    response['ans'] = answers
    response["Time Taken"] = round((time.time() - s),2)
    print(response)
    return response

async def take_time():
    # # time.sleep(4)
    # await asyncio.sleep(4)
    for i in range(100000000):
        o=i
    return str(o)
if __name__=='__main__':
    asyncio.run(test())
  • 1
    What exactly didn't work? – bereal Nov 22 '21 at 14:38
  • Your functions don't actually do anything ``async``. Even then, it's not really clear what you would expect to see as a result: Proper ``async`` code is *concurrent*, not *parallel*; it won't finish a computational task faster than synchronous code. – MisterMiyagi Nov 22 '21 at 14:43
  • @bereal for every return of take_time func its taking 2.5 sec, I want it to run concurrently – Raja Raghudeep Emani Nov 22 '21 at 15:01
  • @MisterMiyagi Not able to understand why it should not work, shouldn't it start looping while the other loop is in process to complete. – Raja Raghudeep Emani Nov 22 '21 at 15:08
  • @RajaRaghudeepEmani then just to rephrase what Miyagi-san said, iterating over a range is a CPU-bound task, it won't get any faster if you just call it in an async loop. You can try using [process pools](https://docs.python.org/3/library/concurrent.futures.html). – bereal Nov 22 '21 at 15:09
  • @bereal thanks for the link ill go through it, actually I was trying to use fastapi and came across an example to extract ocr from multiple images using pytesseract. It worked there with same logic. So is it that pytesseract is somehow not cpu bound – Raja Raghudeep Emani Nov 22 '21 at 15:12
  • 1
    You might want to read through [How does asyncio actually work?](https://stackoverflow.com/questions/49005651/how-does-asyncio-actually-work). – MisterMiyagi Nov 22 '21 at 15:18

0 Answers0