我可以加速嵌套的异步/等待aiohttp代码吗?

2024-03-29 15:43:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在下面的代码中将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))

Tags: 代码inimportloopasynciogetasyncaiohttp
1条回答
网友
1楼 · 发布于 2024-03-29 15:43:41

你需要的是^{}它允许并行运行多个协同程序。在

看起来下面的代码

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)

相关问题 更多 >