2017-06-13 44 views
0

如果我在下面的代码中将in range(1)更改为in range(5),则运行时间将延长大约5倍。我希望从并发中获得更好的数字。我是否设置了错误的代码?我可以加速嵌套的异步/等待aiohttp代码吗?

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)) 
+0

代码也许你应该尝试创建任务,而不是一个圈的名单?异步并不是并发的 – VMAtm

回答

1

你在找什么是asyncio.gather它允许同时运行几个协程。

你将最终看起来像以下

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