Created
June 5, 2021 13:03
-
-
Save biranchi2018/b6f704c66e3f9c4a18471b5b99d68d87 to your computer and use it in GitHub Desktop.
Async await in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from asyncio import run | |
async def sum(): | |
total = 0 | |
for i in range(0,10): | |
print(f'i : {i}') | |
total += i | |
return total | |
async def greeter(name): | |
result = await sum() | |
print(f'Hi, {name} , sum : {result}') | |
return "success" | |
def call(): | |
result = run(greeter('Biranchi')) | |
print(f'call : {result}') | |
call() | |
''' | |
Result : | |
====== | |
i : 0 | |
i : 1 | |
i : 2 | |
i : 3 | |
i : 4 | |
i : 5 | |
i : 6 | |
i : 7 | |
i : 8 | |
i : 9 | |
Hi, Biranchi , sum : 45 | |
call : success | |
''' | |
#====================================================================================== | |
import asyncio | |
async def count(): | |
print("One") | |
await asyncio.sleep(1) | |
print("Two") | |
async def main(): | |
await asyncio.gather(count(), count(), count()) | |
if __name__ == "__main__": | |
import time | |
s = time.perf_counter() | |
asyncio.run(main()) | |
elapsed = time.perf_counter() - s | |
print(f"{__file__} executed in {elapsed:0.2f} seconds.") | |
#====================================================================================== | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment