Skip to content

Instantly share code, notes, and snippets.

@wangkuiyi
Created April 2, 2021 01:36
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 wangkuiyi/493ba31d255177a46de20e482f04ba7f to your computer and use it in GitHub Desktop.
Save wangkuiyi/493ba31d255177a46de20e482f04ba7f to your computer and use it in GitHub Desktop.
Read asynchronously from multiple async generators
import asyncio
from aiostream import stream # You need to pip install aiostream
from datetime import datetime
async def agint(n:int, v:int):
for _ in range(n):
await asyncio.sleep(0.1)
yield v
async def conc():
combine = stream.merge(agint(10, 1), agint(10, 2))
async with combine.stream() as streamer:
t0 = datetime.now()
async for item in streamer:
print(item)
print(datetime.now() - t0)
asyncio.run(conc())
async def sequ():
t0 = datetime.now()
async for item in agint(10, 1):
print(item)
async for item in agint(10, 1):
print(item)
print(datetime.now() - t0)
asyncio.run(sequ())
@wangkuiyi
Copy link
Author

Reading from two interleaved async generators takes the half amount of time of reading sequentially from the two generators one-after-the-other.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment