"""对比 def 路由、async def 阻塞、async def 正确 await 的并发行为。""" from __future__ import annotations import asyncio import time import httpx from fastapi import FastAPI DELAY = 0.05 COUNT = 3 def create_app() -> FastAPI: app = FastAPI() @app.get("/sync") def sync_route() -> dict[str, bool]: time.sleep(DELAY) return {"ok": True} @app.get("/async-block") async def async_block() -> dict[str, bool]: time.sleep(DELAY) return {"ok": True} @app.get("/async-sleep") async def async_sleep() -> dict[str, bool]: await asyncio.sleep(DELAY) return {"ok": True} return app async def measure(path: str, count: int = COUNT) -> float: transport = httpx.ASGITransport(app=create_app()) async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: started = time.perf_counter() await asyncio.gather(*(client.get(path) for _ in range(count))) return time.perf_counter() - started async def run_all() -> tuple[float, float, float]: return ( await measure("/sync"), await measure("/async-block"), await measure("/async-sleep"), ) def main() -> None: sync_time, block_time, sleep_time = asyncio.run(run_all()) print(f"sync: {sync_time:.2f}s") print(f"async_block: {block_time:.2f}s") print(f"async_sleep: {sleep_time:.2f}s") print(f"sync_concurrent: {sync_time < 0.12}") print(f"async_block_serial: {block_time > 0.12}") print(f"async_sleep_concurrent: {sleep_time < 0.12}") if __name__ == "__main__": main()