简体   繁体   English

asyncio.gather 与列表理解

[英]asyncio.gather vs list comprehension

In the following code, are get_all_details_1 and get_all_details_2 behave the same?在下面的代码中, get_all_details_1get_all_details_2的行为是否相同?

async def get_details(category, limit):
    async with limit:
        # ... 

limit = asyncio.Semaphore(4)
a_list = .... # a big list

async def get_all_details_1():
    b_list = await asyncio.gather(*[get_details(x, limit) for x in a_list])
    # ....


async def get_all_details_2():
    b_list = [await get_details(x, limit) for x in a_list]
    # ....

Absolutely not: Example:绝对不是: 示例:

import asyncio
import time

async def slowtask():
    await asyncio.sleep(1)

async def gather():
    await asyncio.gather(*[slowtask() for _ in range(10)])

async def listcomp():
    [await slowtask() for _ in range(10)]

start = time.time()
asyncio.run(gather())
print("gather", time.time() - start)

start = time.time()
asyncio.run(listcomp())
print("listcomp", time.time() - start)

gives us:给我们:

gather 1.0030405521392822
listcomp 10.015443325042725

asyncio.gather properly allows multiple async tasks to run asynchronously while the list comprehension await s one after the other, leading to effectively serial code. asyncio.gather正确地允许多个异步任务异步运行,而列表理解await一个接一个地运行,从而有效地生成串行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM