Created
April 2, 2021 01:36
-
-
Save wangkuiyi/493ba31d255177a46de20e482f04ba7f to your computer and use it in GitHub Desktop.
Read asynchronously from multiple async generators
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 | |
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reading from two interleaved async generators takes the half amount of time of reading sequentially from the two generators one-after-the-other.