我可以加速嵌套 async/await aiohttp 代码吗?

Can I speed up nested async/await aiohttp code?

如果我在下面的代码中将 in range(1) 更改为 in range(5),则 运行 需要大约 5 倍的时间。我希望从并发性中获得更好的数字。我是否设置了错误的代码?

import asyncio
import aiohttp

async def fetch(session):
    async with session.get("http://www.example.com") as res:
        await res.text()

async def foo(session):
    for i in range(10):
        await fetch(session)

async def main(loop):
    async with aiohttp.ClientSession(loop = loop) as session:
        for i in range(1):
            await foo(session)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

您正在寻找的是 asyncio.gather 它允许 运行 多个并行的协程。

您最终会得到如下所示的代码

def main():
    # init session
    coroutines = list()
    for i in range(5):
        coroutine = fetch(session)  # XXX: mind the fact that there is no await keyword here
        coroutines.append(coroutine)
    await asyncio.gather(*coroutines)