Skip to content

Instantly share code, notes, and snippets.

@nmchenry01
Last active November 23, 2021 20:12
Show Gist options
  • Select an option

  • Save nmchenry01/a914484d21de597bff12aa77ebd413be to your computer and use it in GitHub Desktop.

Select an option

Save nmchenry01/a914484d21de597bff12aa77ebd413be to your computer and use it in GitHub Desktop.
Running multiple coroutines concurrently
import asyncio
import time
async def me_first():
await asyncio.sleep(1)
return "I'm first!"
async def me_second():
await asyncio.sleep(1)
return "Then me!"
async def me_third():
await asyncio.sleep(1)
return "And finally me!"
async def main():
start = time.perf_counter()
# Init all coroutines
first_coroutine = me_first()
second_coroutine = me_second()
third_coroutine = me_third()
# Schedule all coroutines to run concurrently and wait on all to return
await asyncio.gather(*[first_coroutine, second_coroutine, third_coroutine])
end = time.perf_counter()
print(f"It took {end - start} seconds to complete all operations\n")
asyncio.run(main())
# Output:
#
# It took 1.0012879579999208 seconds to complete all operations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment