python - asyncio.gather 与列表理解
问题描述
在下面的代码中,是否get_all_details_1
和get_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]
# ....
解决方案
绝对不!例子:
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)
给我们:
gather 1.0030405521392822
listcomp 10.015443325042725
asyncio.gather
正确地允许多个异步任务异步运行,而列表理解await
一个接一个,导致有效的串行代码。
推荐阅读
- ssis - 使用 SSIS 将数据从 Dynamic 365 增量复制到 Oracle
- android - Android 11 + Kotlin:读取 .zip 文件
- python - 如何通过 ffmpeg-python 获取 service_name 和程序列表
- linux - 通过移动分组列变量的差异来平均列的awk
- javascript - 在 Material UI DataGrid 单元格中显示完整的 ApexChart 工具提示
- mysql - MySQL 中的 SELECT 和 CONCAT
- python - 错误:找不到满足要求 ctranslate2 的版本
- powershell - Powershell如何知道列表的元素是否连续编号
- android - E/AndroidRuntime:致命异常:pool-5-thread-1
- postgresql - DO块中的Postgres动态限制偏移