Last active
November 23, 2021 20:12
-
-
Save nmchenry01/a914484d21de597bff12aa77ebd413be to your computer and use it in GitHub Desktop.
Running multiple coroutines concurrently
This file contains hidden or 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
| 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