|
14 | 14 |
|
15 | 15 | import asyncio |
16 | 16 | import socket |
17 | | -import time |
18 | 17 |
|
19 | 18 | import httpx |
20 | 19 | import pyperf |
@@ -44,41 +43,42 @@ async def get_item(item_id: int): |
44 | 43 | } |
45 | 44 |
|
46 | 45 |
|
47 | | -async def run_server_and_benchmark(loops): |
| 46 | +def bench_fastapi(loops): |
48 | 47 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
49 | 48 | s.bind((HOST, 0)) |
50 | 49 | s.listen(1) |
51 | 50 | port = s.getsockname()[1] |
52 | 51 |
|
| 52 | + # Setup server |
53 | 53 | config = uvicorn.Config(app, host=HOST, port=port, log_level="error") |
54 | 54 | server = uvicorn.Server(config) |
55 | | - server_task = asyncio.create_task(server.serve()) |
56 | 55 |
|
57 | | - await asyncio.sleep(0.5) |
| 56 | + async def run_benchmark(): |
| 57 | + server_task = asyncio.create_task(server.serve()) |
| 58 | + await asyncio.sleep(0.5) |
58 | 59 |
|
59 | | - async with httpx.AsyncClient() as client: |
60 | | - t0 = time.perf_counter() |
| 60 | + async with httpx.AsyncClient() as client: |
| 61 | + t0 = pyperf.perf_counter() |
61 | 62 |
|
62 | | - for i in range(loops): |
63 | | - tasks = [ |
64 | | - client.get(f"http://{HOST}:{port}/items/{i}") |
65 | | - for _ in range(CONCURRENCY) |
66 | | - ] |
67 | | - responses = await asyncio.gather(*tasks) |
68 | | - for response in responses: |
69 | | - response.raise_for_status() |
70 | | - data = response.json() |
71 | | - assert data["id"] == i |
72 | | - assert "tags" in data |
| 63 | + for i in range(loops): |
| 64 | + tasks = [ |
| 65 | + client.get(f"http://{HOST}:{port}/items/{i}") |
| 66 | + for _ in range(CONCURRENCY) |
| 67 | + ] |
| 68 | + responses = await asyncio.gather(*tasks) |
| 69 | + for response in responses: |
| 70 | + response.raise_for_status() |
| 71 | + data = response.json() |
| 72 | + assert data["id"] == i |
| 73 | + assert "tags" in data |
73 | 74 |
|
74 | | - elapsed = time.perf_counter() - t0 |
| 75 | + elapsed = pyperf.perf_counter() - t0 |
75 | 76 |
|
76 | | - server.should_exit = True |
77 | | - await server_task |
78 | | - return elapsed |
| 77 | + server.should_exit = True |
| 78 | + await server_task |
| 79 | + return elapsed |
79 | 80 |
|
80 | | -def bench_fastapi(loops): |
81 | | - return asyncio.run(run_server_and_benchmark(loops)) |
| 81 | + return asyncio.run(run_benchmark()) |
82 | 82 |
|
83 | 83 |
|
84 | 84 | if __name__ == "__main__": |
|
0 commit comments