Python asyncio.gather与列表理解
在以下代码中,Python asyncio.gather与列表理解,python,Python,在以下代码中,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_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]
# ....
绝对不是!例如:
导入异步IO
导入时间
异步def slowtask():
等待asyncio.sleep(1)
异步def gather():
等待asyncio.gather(*[slowtask()用于范围(10)])
异步def listcomp():
[等待范围内(10)的slowtask()]
开始=时间。时间()
asyncio.run(gather())
打印(“收集”,time.time()-start)
开始=时间。时间()
asyncio.run(listcomp())
打印(“listcomp”,time.time()-start)
给了我们:
gather 1.0030405521392822
listcomp 10.015443325042725
asyncio.gather
正确地允许多个异步任务异步运行,同时列表理解一个接一个地等待
s,从而生成有效的串行代码。不完全正确,但输出相同。。。收集速度可能有点快,这对asyncio是个问题。收集(…)
接受一个很长的参数列表?@ca9163d9我不明白为什么会这样。