Python 3.12.8 中的 Asyncio 任务创建延迟与 Python 3.10 相比
Python 版本: 3.12.8 使用 asyncio.gather 并发执行异步 HTTP 请求时,任务创建会出现明显的延迟,大约每个任务一秒钟,这是不合理的。在 Python 3.10 中,相同的代码运行正常,任务会被同时创建和执行,不会出现这种延迟。 import asyncio import time import httpx async def test_request(brand_id: int): url = "https://httpbin.org/delay/1" async with httpx.AsyncClient() as client: response = await client.get(url) return response.text async def test(task_id: int): print(f"{time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())} task {task_id} start") response = await test_request(brand_id=task_id) print(f"{time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())} task {task_id} end") async def batch_test(task_ids: list[int]): print(task_ids) tasks = [asyncio.create_task(test(task_id)) for task_id in task_ids] await asyncio.gather(*tasks) if __name__ == '__main__': task_ids = [i for i in range(10)] asyncio.run(batch_test(task_ids))
我不知道为什么会出现这种情况
内容来源: encode/httpx