Skip to content

Instantly share code, notes, and snippets.

@mhsharifi96
Last active March 8, 2022 11:47
Show Gist options
  • Save mhsharifi96/61d0ebb240d0d265c10b31c230359409 to your computer and use it in GitHub Desktop.
Save mhsharifi96/61d0ebb240d0d265c10b31c230359409 to your computer and use it in GitHub Desktop.
simple example with asyncio, that show how async function works
import asyncio
import time
async def sample():
start_time = time.time()
print('start')
await asyncio.sleep(1)
await asyncio.sleep(2)
print('after 2s sleep on sample ')
await asyncio.sleep(1)
end_time = time.time() - start_time
print('sample function Total Time : ',end_time)
async def sample2():
start_time = time.time()
await asyncio.sleep(2)
await asyncio.sleep(3)
print('after 3s sleep on sample2')
await asyncio.sleep(2)
end_time = time.time() - start_time
print('sample2 function Total Time : ',end_time)
async def main():
await asyncio.gather(sample(), sample2())
if __name__ == "__main__":
s = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - s
print(f"{__file__} executed in {elapsed:0.2f} seconds.")
# output :
# sample function Total Time : 4.015647888183594
# sample2 function Total Time : 6.015649080276489
# C:\Users\sample\test_async.py executed in 6.02 seconds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment