|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import time |
| 4 | +from contextlib import contextmanager |
| 5 | +from typing import Any, Coroutine, Iterator |
| 6 | + |
| 7 | +import aiohttp |
| 8 | +import matplotlib.pyplot as plt |
| 9 | +import pyinstrument |
| 10 | +from matplotlib.axes import Axes |
| 11 | + |
| 12 | +import httpcore |
| 13 | + |
| 14 | +PORT = 1234 |
| 15 | +URL = f"http://localhost:{PORT}/req" |
| 16 | +REPEATS = 10 |
| 17 | +REQUESTS = 500 |
| 18 | +CONCURRENCY = 20 |
| 19 | +POOL_LIMIT = 100 |
| 20 | +PROFILE = False |
| 21 | +os.environ["HTTPCORE_PREFER_ANYIO"] = "0" |
| 22 | + |
| 23 | + |
| 24 | +def duration(start: float) -> int: |
| 25 | + return int((time.monotonic() - start) * 1000) |
| 26 | + |
| 27 | + |
| 28 | +@contextmanager |
| 29 | +def profile(): |
| 30 | + if not PROFILE: |
| 31 | + yield |
| 32 | + return |
| 33 | + with pyinstrument.Profiler() as profiler: |
| 34 | + yield |
| 35 | + profiler.open_in_browser() |
| 36 | + |
| 37 | + |
| 38 | +async def gather_limited_concurrency( |
| 39 | + coros: Iterator[Coroutine[Any, Any, Any]], concurrency: int = CONCURRENCY |
| 40 | +) -> None: |
| 41 | + sem = asyncio.Semaphore(concurrency) |
| 42 | + |
| 43 | + async def coro_with_sem(coro: Coroutine[Any, Any, Any]) -> None: |
| 44 | + async with sem: |
| 45 | + await coro |
| 46 | + |
| 47 | + await asyncio.gather(*(coro_with_sem(c) for c in coros)) |
| 48 | + |
| 49 | + |
| 50 | +async def run_requests(axis: Axes) -> None: |
| 51 | + async def httpcore_get( |
| 52 | + pool: httpcore.AsyncConnectionPool, timings: list[int] |
| 53 | + ) -> None: |
| 54 | + start = time.monotonic() |
| 55 | + res = await pool.request("GET", URL) |
| 56 | + assert len(await res.aread()) == 2000 |
| 57 | + assert res.status == 200, f"status_code={res.status}" |
| 58 | + timings.append(duration(start)) |
| 59 | + |
| 60 | + async def aiohttp_get(session: aiohttp.ClientSession, timings: list[int]) -> None: |
| 61 | + start = time.monotonic() |
| 62 | + async with session.request("GET", URL) as res: |
| 63 | + assert len(await res.read()) == 2000 |
| 64 | + assert res.status == 200, f"status={res.status}" |
| 65 | + timings.append(duration(start)) |
| 66 | + |
| 67 | + async with httpcore.AsyncConnectionPool(max_connections=POOL_LIMIT) as pool: |
| 68 | + # warmup |
| 69 | + await gather_limited_concurrency( |
| 70 | + (httpcore_get(pool, []) for _ in range(REQUESTS)), CONCURRENCY * 2 |
| 71 | + ) |
| 72 | + |
| 73 | + timings: list[int] = [] |
| 74 | + start = time.monotonic() |
| 75 | + with profile(): |
| 76 | + for _ in range(REPEATS): |
| 77 | + await gather_limited_concurrency( |
| 78 | + (httpcore_get(pool, timings) for _ in range(REQUESTS)) |
| 79 | + ) |
| 80 | + axis.plot( |
| 81 | + [*range(len(timings))], timings, label=f"httpcore (tot={duration(start)}ms)" |
| 82 | + ) |
| 83 | + |
| 84 | + connector = aiohttp.TCPConnector(limit=POOL_LIMIT) |
| 85 | + async with aiohttp.ClientSession(connector=connector) as session: |
| 86 | + # warmup |
| 87 | + await gather_limited_concurrency( |
| 88 | + (aiohttp_get(session, []) for _ in range(REQUESTS)), CONCURRENCY * 2 |
| 89 | + ) |
| 90 | + |
| 91 | + timings = [] |
| 92 | + start = time.monotonic() |
| 93 | + for _ in range(REPEATS): |
| 94 | + await gather_limited_concurrency( |
| 95 | + (aiohttp_get(session, timings) for _ in range(REQUESTS)) |
| 96 | + ) |
| 97 | + axis.plot( |
| 98 | + [*range(len(timings))], timings, label=f"aiohttp (tot={duration(start)}ms)" |
| 99 | + ) |
| 100 | + |
| 101 | + |
| 102 | +def main() -> None: |
| 103 | + fig, ax = plt.subplots() |
| 104 | + asyncio.run(run_requests(ax)) |
| 105 | + plt.legend(loc="upper left") |
| 106 | + ax.set_xlabel("# request") |
| 107 | + ax.set_ylabel("[ms]") |
| 108 | + plt.show() |
| 109 | + print("DONE", flush=True) |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + main() |
0 commit comments