Skip to content

Instantly share code, notes, and snippets.

@matin
Last active August 17, 2020 18:44
Show Gist options
  • Save matin/f4d36fe2397612bf49ec360d9354a2f8 to your computer and use it in GitHub Desktop.
Save matin/f4d36fe2397612bf49ec360d9354a2f8 to your computer and use it in GitHub Desktop.
import asyncio
import time
from functools import partial
from typing import Any, Callable, Optional
async def create_awaitable(func: Callable, *args, **kwargs) -> Any:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, partial(func, *args, **kwargs))
def hello(delay, first_name, last_name = None):
time.sleep(delay)
if last_name:
full_name = f'{first_name} {last_name}'
else:
full_name = first_name
return f'hello {full_name}!'
# blocking
hellos = []
start = time.time()
for resp in [hello(2, 'matin', 'tamizi'), hello(1, 'manuel')]:
hellos.append(resp)
assert round(time.time() - start) == 3
assert hellos == ['hello matin tamizi!', 'hello manuel!']
# asyncio.gather
first = create_awaitable(hello, 2, 'matin', 'tamizi')
second = create_awaitable(hello, 1, 'manuel')
start = time.time()
hellos = await asyncio.gather(first, second)
assert round(time.time() - start) == 2
# same order as blocking
assert hellos == ['hello matin tamizi!', 'hello manuel!']
# asyncio.as_completed
first = create_awaitable(hello, 2, 'matin', 'tamizi')
second = create_awaitable(hello, 1, 'manuel')
hellos = []
start = time.time()
for coro in asyncio.as_completed([first, second]):
hellos.append(await coro)
assert round(time.time() - start) == 2
# ordered by whichever was fastest
assert hellos == ['hello manuel!', 'hello matin tamizi!']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment