Skip to content

Instantly share code, notes, and snippets.

@xjcl
Created January 4, 2020 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjcl/75481ab8df552aaaf325680fe8d480f9 to your computer and use it in GitHub Desktop.
Save xjcl/75481ab8df552aaaf325680fe8d480f9 to your computer and use it in GitHub Desktop.
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