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

时间:2017-06-13 00:30:15

标签: python asynchronous async-await aiohttp

如果我在下面的代码中将trait BaseTrait[A, T[X] <: BaseTrait[X, T]] { this: T[A] => def someMethod[B](f: A => T[B]): T[B] } class Concrete[A] extends BaseTrait[A, Concrete]{ def someMethod[B](f: A => Concrete[B]): Concrete[B] = ??? } //class DoesNotCompile[A] extends BaseTrait[Concrete, A]{ // def someMethod[B](f: A => Concrete[B]): Concrete[B] = ??? //} //class DoesNotCompile2[A] extends BaseTrait[DoesNotCompile2, A]{ // def someMethod[B](f: A => Concrete[B]): Concrete[B] = ??? //} object Ex { val concrete: Concrete[List[Int]] = new Concrete[List[Int]] val concrete2: Concrete[String] = concrete.someMethod(_ => new Concrete[String]) } 更改为in range(1),则运行时间大约需要5倍。我希望从并发中获得更好的数字。我是否错误地设置了此代码?

in range(5)

1 个答案:

答案 0 :(得分:2)

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