"""피드·날씨 API 동시 접속 부하 측정. 예: python scripts/load_test.py --base http://localhost:9810 --regions 1114000000,4113500000 --users 10,50,100""" import argparse import asyncio import statistics import time import httpx PATHS = ["/v1/feed", "/v1/weather/now", "/v1/weather/today", "/v1/index/list", "/v1/sky", "/v1/week"] async def _user(client: httpx.AsyncClient, regions: list[str], deadline: float, out: list[tuple[str, float, int]]) -> None: i = 0 while time.perf_counter() < deadline: path, region = PATHS[i % len(PATHS)], regions[i % len(regions)] i += 1 start = time.perf_counter() try: res = await client.get(path, params={"region": region}) code = res.status_code if res.status_code != 200 or res.json()["result"]["success"] else 299 except (httpx.HTTPError, ValueError): code = 0 out.append((path, time.perf_counter() - start, code)) def _pct(xs: list[float], p: float) -> float: return sorted(xs)[min(len(xs) - 1, int(len(xs) * p))] * 1000 async def run(base: str, regions: list[str], users: int, seconds: float) -> None: out: list[tuple[str, float, int]] = [] limits = httpx.Limits(max_connections=users, max_keepalive_connections=users) async with httpx.AsyncClient(base_url=base, timeout=120, limits=limits) as client: deadline = time.perf_counter() + seconds await asyncio.gather(*[_user(client, regions[u % len(regions):] + regions[:u % len(regions)], deadline, out) for u in range(users)]) lat = [d for _, d, _ in out] bad = sum(1 for *_, c in out if c != 200) print(f"users {users:>3} req {len(out):>5} rps {len(out) / seconds:6.1f} p50 {_pct(lat, .5):6.0f}ms p95 {_pct(lat, .95):6.0f}ms " f"p99 {_pct(lat, .99):6.0f}ms max {max(lat) * 1000:6.0f}ms 실패 {bad} ({bad / len(out):.1%})") for path in PATHS: xs = [d for p, d, _ in out if p == path] if xs: print(f" {path:<20} p50 {statistics.median(xs) * 1000:6.0f}ms p95 {_pct(xs, .95):6.0f}ms") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--base", default="http://localhost:9810") ap.add_argument("--regions", required=True) ap.add_argument("--users", default="10,50,100") ap.add_argument("--seconds", type=float, default=20) a = ap.parse_args() for n in (int(x) for x in a.users.split(",")): asyncio.run(run(a.base, a.regions.split(","), n, a.seconds)) if __name__ == "__main__": main()