【问题标题】:Can I speed up nested async/await aiohttp code?我可以加快嵌套的 async/await aiohttp 代码吗?
【发布时间】:2018-08-20 04:04:48
【问题描述】:

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

【问题讨论】:

  • 也许您应该尝试创建一个任务列表而不是一个循环?而且异步不是并发

标签: python asynchronous async-await aiohttp


【解决方案1】:

您正在寻找的是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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2018-06-04
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多