Created
January 4, 2020 20:08
-
-
Save xjcl/75481ab8df552aaaf325680fe8d480f9 to your computer and use it in GitHub Desktop.
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
import asyncio | |
import time | |
async def say_after(delay, what): | |
await asyncio.sleep(delay) | |
print(what) | |
async def use_await(): | |
await say_after(3, 'world') | |
await say_after(2, 'hello') | |
print(f"use_await finished at t={time.time() - start} seconds") | |
async def use_tasks(): | |
task_a = asyncio.create_task(say_after(3, 'world')) | |
task_b = asyncio.create_task(say_after(2, 'hello')) | |
await task_a | |
await task_b | |
print(f"use_tasks finished at t={time.time() - start} seconds") | |
start = time.time() | |
asyncio.run(use_await()) # Prints 'world hello' in 5 seconds | |
asyncio.run(use_tasks()) # Prints 'hello world' in 3 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment