requests.post):即使在 ThreadPoolExecutor 中,每个线程也是阻塞等待响应asyncio + httpx 实现真正的异步并发# ❌ 旧版本(同步阻塞)
response = requests.post(url, json=data)
# ✅ 新版本(异步非阻塞)
async with httpx.AsyncClient() as client:
response = await client.post(url, json=data)
# 创建所有异步任务
coroutines = [
self.extract_part_info(client, image_base64, prompt, task_name)
for task_name, prompt in tasks.items()
]
# 真正并发执行(5 个请求同时发送)
results_list = await asyncio.gather(*coroutines)
假设每个 OCR 请求耗时 10 秒:
| 实现方式 | 执行时间 | 说明 |
|---|---|---|
| 同步串行 | ~50 秒 | 5 个请求 × 10 秒 = 50 秒 |
| 多线程 | ~45-50 秒 | 受 GIL 限制,提升有限 |
| 异步并发 | ~10-12 秒 | 真正并发,接近单个请求时间 |
理论加速比:约 4-5 倍 🚀
# 启动 FastAPI 服务
python -m model.model_api
python test_async_performance.py
你会看到类似这样的输出:
============================================================
[0.000s] 🎯 开始异步并发处理...
============================================================
[0.123s] 🚀 开始任务: name
[0.124s] 🚀 开始任务: tag
[0.125s] 🚀 开始任务: risk_notice
[0.126s] 🚀 开始任务: pre_notice
[0.127s] 🚀 开始任务: suppliers
[10.456s] ✅ 完成任务: name (耗时: 10.333s)
[10.789s] ✅ 完成任务: tag (耗时: 10.665s)
[11.012s] ✅ 完成任务: risk_notice (耗时: 10.887s)
[11.234s] ✅ 完成任务: pre_notice (耗时: 11.108s)
[11.567s] ✅ 完成任务: suppliers (耗时: 11.440s)
============================================================
⏱️ 总推理时间: 11.567000 秒
📊 平均每个任务: 2.313400 秒
🚀 并发加速比: ~5.0x (理论值)
============================================================
关键观察点:
from PIL import Image
from agent.agent import OcrAgent
image = Image.open("test.jpg").convert("RGB")
agent = OcrAgent()
result = agent.agent_ocr(image) # 自动使用异步实现
import asyncio
from PIL import Image
from agent.agent import OcrAgent
async def main():
image = Image.open("test.jpg").convert("RGB")
agent = OcrAgent()
result = await agent.agent_ocr_async(image)
return result
result = asyncio.run(main())
虽然客户端现在是真正并发,但服务端的处理能力取决于:
model_api.py 中设置了 max_concurrent=10可能的原因:
如果需要更快的速度:
agent/agent.py - 改用 asyncio + httpxtest_async_performance.py - 性能测试脚本requirements_async.txt - 异步依赖pip install httpx>=0.25.0
pip install httpx)python test_async_performance.py通过这次优化,我们实现了:
现在运行 test_async_performance.py,你应该能清楚地看到并发效果!🚀