diff --git a/benchmark_routing.py b/benchmark_routing.py index fbfdf178e..724c8b430 100644 --- a/benchmark_routing.py +++ b/benchmark_routing.py @@ -1,4 +1,5 @@ import time + from fastapi import APIRouter, FastAPI # Setup Router @@ -7,27 +8,35 @@ router = APIRouter() # 50 Static Routes for i in range(50): + @router.get(f"/static-{i}") def static_route(i=i): return {"route": f"static-{i}"} + # 50 Dynamic Routes for i in range(50): + @router.get(f"/dynamic-{i}/{{item_id}}") def dynamic_route(item_id: int, i=i): return {"route": f"dynamic-{i}", "item_id": item_id} + app.include_router(router) -import anyio from contextlib import AsyncExitStack +import anyio + + # Mock ASGI stack async def mock_receive(): return {"type": "http.request", "body": b"", "more_body": False} + async def mock_send(message): pass + scope_static = { "type": "http", "method": "GET", @@ -54,6 +63,7 @@ scope_dynamic = { "fastapi_function_astack": AsyncExitStack(), } + async def run_benchmark(): # Warmup for _ in range(100): @@ -82,7 +92,7 @@ async def run_benchmark(): print(f"Speedup: {cache_disabled_time / cache_enabled_time:.2f}x") print("\nRunning Dynamic Route Benchmark (10,000 iterations)...") - + # Caching has no effect on dynamic routes start_time = time.perf_counter() for _ in range(10000): @@ -90,5 +100,6 @@ async def run_benchmark(): dynamic_time = time.perf_counter() - start_time print(f"Dynamic Route time: {dynamic_time:.4f} seconds") + if __name__ == "__main__": anyio.run(run_benchmark)