Debian Codegraph @

benchmark/bench.py

raw
1 #!/usr/bin/env python3
2 """
3 caio benchmark — latency distribution & throughput.
4
5 Two orthogonal sweeps for each backend:
6
7 1. concurrency sweep — fix chunk=16 KB, vary in-flight ops: 1…512
8 2. chunk-size sweep — fix concurrency=64, vary chunk: 4 KB…1 MB
9
10 Metrics per cell: ops/s · MB/s · mean · p50 · p95 · p99 · p999 (ms)
11
12 Usage:
13 CAIO_BENCH_DATA=/tmp/caio-bench CAIO_RESULTS=/tmp/results uv run python bench.py
14 """
15 import asyncio
16 import importlib
17 import itertools
18 import os
19 import pathlib
20 import random
21 import sys
22 import tempfile
23 import time
24 from typing import Callable, Iterator, List, Tuple
25
26 DATA_DIR = pathlib.Path(os.environ.get("CAIO_BENCH_DATA", "data"))
27 RESULTS_DIR = pathlib.Path(os.environ.get("CAIO_RESULTS", "/tmp/results"))
28
29 TOTAL_OPS = 10_000
30 WARMUP_OPS = 500
31 MAX_REQUESTS = 4096
32
33 # sweep 1 — vary concurrency, fixed chunk
34 CONC_SWEEP_CHUNK = 16 * 1024
35 CONC_SWEEP = [1, 4, 16, 64, 256, 512, 1024, 2048, 4096]
36
37 # sweep 2 — vary chunk size, fixed concurrency
38 CHUNK_SWEEP_CONC = 64
39 CHUNK_SWEEP_SIZES = [4 * 1024, 16 * 1024, 64 * 1024, 256 * 1024, 1024 * 1024, 4 * 1024 * 1024]
40
41 BACKENDS = [
42 ("linux_uring", "caio.linux_uring_asyncio", "AsyncioContext"),
43 ("linux_aio", "caio.linux_aio_asyncio", "AsyncioContext"),
44 ("thread_aio", "caio.thread_aio_asyncio", "AsyncioContext"),
45 ("python_aio", "caio.python_aio_asyncio", "AsyncioContext"),
46 ]
47
48
49 # ── stats ─────────────────────────────────────────────────────────────────────
50
51 def pct(data: List[float], p: float) -> float:
52 s = sorted(data)
53 return s[min(int(len(s) * p), len(s) - 1)]
54
55
56 def calc_stats(lats: List[float], wall: float, chunk: int, n_total: int) -> dict:
57 ops = n_total / wall
58 return dict(
59 n_ops = n_total,
60 wall_s = wall,
61 ops_s = ops,
62 mb_s = ops * chunk / 1e6,
63 mean = sum(lats) / len(lats) * 1e3,
64 p50 = pct(lats, 0.500) * 1e3,
65 p95 = pct(lats, 0.950) * 1e3,
66 p99 = pct(lats, 0.990) * 1e3,
67 p999 = pct(lats, 0.999) * 1e3,
68 )
69
70
71 # ── I/O sources ───────────────────────────────────────────────────────────────
72
73 class ReadPool:
74 def __init__(self):
75 self._fps = []
76 self._fds: List[Tuple[int, int]] = []
77
78 def open(self):
79 paths = sorted(DATA_DIR.glob("*.bin"))
80 if not paths:
81 sys.exit(f"No .bin files in {DATA_DIR}. Run gen_data.py first.")
82 for p in paths:
83 fp = open(p, "rb")
84 self._fps.append(fp)
85 self._fds.append((fp.fileno(), p.stat().st_size))
86
87 def args(self, chunk: int) -> Tuple[int, int, int]:
88 fd, size = random.choice(self._fds)
89 hi = max(0, size - chunk)
90 offset = (random.randint(0, hi) >> 12) << 12 # 4 KB aligned
91 return chunk, fd, offset
92
93 def pregenerate(self, n: int, chunk: int) -> Iterator[Tuple[int, int, int]]:
94 return itertools.cycle([self.args(chunk) for _ in range(n)])
95
96 def pregenerate_seq(self, chunk: int) -> Iterator[Tuple[int, int, int]]:
97 """Sequential read offsets cycling through all open files."""
98 args = []
99 for fd, size in self._fds:
100 offset = 0
101 while offset + chunk <= size:
102 args.append((chunk, fd, offset))
103 offset += chunk
104 if not args:
105 return self.pregenerate(1, chunk)
106 return itertools.cycle(args)
107
108 def close(self):
109 for fp in self._fps:
110 fp.close()
111
112
113 class WriteTarget:
114 # big enough for any chunk × (ops + warmup)
115 SIZE = 1024 * 1024 * 1024 # 1 GB preallocated sparse file
116
117 def __init__(self):
118 self._fp = tempfile.NamedTemporaryFile(delete=False)
119 self._fp.seek(self.SIZE - 1)
120 self._fp.write(b"\x00")
121 self._fp.flush()
122 self.fd = self._fp.fileno()
123 self._path = pathlib.Path(self._fp.name)
124 self._bufs: dict[int, bytes] = {}
125
126 def args(self, chunk: int) -> Tuple[bytes, int, int]:
127 if chunk not in self._bufs:
128 self._bufs[chunk] = os.urandom(chunk)
129 hi = self.SIZE - chunk
130 offset = (random.randint(0, hi) >> 12) << 12
131 return self._bufs[chunk], self.fd, offset
132
133 def pregenerate(self, n: int, chunk: int) -> Iterator[Tuple[bytes, int, int]]:
134 return itertools.cycle([self.args(chunk) for _ in range(n)])
135
136 def pregenerate_seq(self, chunk: int) -> Iterator[Tuple[bytes, int, int]]:
137 """Sequential write offsets from 0 to SIZE."""
138 if chunk not in self._bufs:
139 self._bufs[chunk] = os.urandom(chunk)
140 n_slots = self.SIZE // chunk
141 args = [(self._bufs[chunk], self.fd, i * chunk) for i in range(n_slots)]
142 return itertools.cycle(args)
143
144 def close(self):
145 self._fp.close()
146 self._path.unlink(missing_ok=True)
147
148
149 # ── engine ────────────────────────────────────────────────────────────────────
150
151 SAMPLE_RATE = 0.1 # time 10% of ops, rest run without perf_counter overhead
152
153
154 async def run(
155 ctx,
156 concurrency: int,
157 n: int,
158 op_fn: Callable,
159 warmup: int,
160 ) -> Tuple[List[float], float]:
161 """
162 Run op_fn(ctx) exactly n times with `concurrency` ops in-flight at most.
163
164 Uses a sliding window: exactly `concurrency` tasks exist at any time,
165 a new one is spawned as soon as any completes. No semaphore needed.
166
167 Only a fraction (SAMPLE_RATE) of ops are individually timed to avoid
168 polluting the measurement with clock overhead. Throughput is always
169 derived from wall time.
170
171 Returns (sampled_latencies_in_seconds, wall_clock_seconds).
172 """
173
174 async def timed() -> float:
175 t = time.perf_counter()
176 await op_fn(ctx)
177 return time.perf_counter() - t
178
179 async def untimed() -> float:
180 await op_fn(ctx)
181 return 0.0
182
183 sampled: set = set() # tasks whose result is a real latency
184 _perf_counter = time.perf_counter
185
186 async def _drain(pending, collect=None):
187 done, pending = await asyncio.wait(
188 pending, return_when=asyncio.FIRST_COMPLETED,
189 )
190 if collect is not None:
191 for task in done:
192 if task in sampled:
193 collect.append(task.result())
194 sampled.discard(task)
195 else:
196 sampled.difference_update(done)
197 return pending
198
199 # Warmup — sliding window, discard results
200 if warmup:
201 pending: set = set()
202 left = warmup
203 while left > 0 or pending:
204 while len(pending) < concurrency and left > 0:
205 pending.add(asyncio.create_task(untimed()))
206 left -= 1
207 if pending:
208 pending = await _drain(pending)
209
210 # Decide which ops to sample (pre-generate for zero per-op overhead)
211 sample_mask = bytearray(1 if random.random() < SAMPLE_RATE else 0 for _ in range(n))
212
213 # Measurement — sliding window, sampled latencies
214 latencies: List[float] = []
215 pending = set()
216 idx = 0
217
218 t0 = _perf_counter()
219 while idx < n or pending:
220 while len(pending) < concurrency and idx < n:
221 if sample_mask[idx]:
222 task = asyncio.create_task(timed())
223 sampled.add(task)
224 else:
225 task = asyncio.create_task(untimed())
226 pending.add(task)
227 idx += 1
228 if pending:
229 pending = await _drain(pending, latencies)
230 wall = _perf_counter() - t0
231
232 return latencies, wall
233
234
235 # ── formatting ────────────────────────────────────────────────────────────────
236
237 def _hdr(pivot_label: str, pivot_width: int) -> str:
238 return (
239 f"{'backend':<14} {'op':<5} {pivot_label:>{pivot_width}}"
240 f" {'ops/s':>8} {'MB/s':>6} {'wall':>6}"
241 f" {'mean':>7} {'p50':>7} {'p95':>7} {'p99':>7} {'p999':>8} (ms)"
242 )
243
244
245 def _row(backend: str, op: str, pivot: str, pivot_w: int, s: dict) -> str:
246 return (
247 f"{backend:<14} {op:<5} {pivot:>{pivot_w}}"
248 f" {s['ops_s']:>8.0f} {s['mb_s']:>6.1f} {s['wall_s']:>5.2f}s"
249 f" {s['mean']:>7.3f} {s['p50']:>7.3f}"
250 f" {s['p95']:>7.3f} {s['p99']:>7.3f} {s['p999']:>8.3f}"
251 )
252
253
254 # ── sweeps ────────────────────────────────────────────────────────────────────
255
256 async def sweep_concurrency(
257 name: str, CtxCls, pool: ReadPool, write: WriteTarget,
258 access: str = "rand",
259 ) -> List[str]:
260 """Vary concurrency at fixed chunk size."""
261 csv: List[str] = []
262 chunk = CONC_SWEEP_CHUNK
263 total = TOTAL_OPS + WARMUP_OPS
264 sweep_tag = f"conc_sweep_{access}"
265
266 for conc in CONC_SWEEP:
267 ctx = CtxCls(max_requests=MAX_REQUESTS)
268 pivot = str(conc)
269 if access == "seq":
270 read_it = pool.pregenerate_seq(chunk)
271 write_it = write.pregenerate_seq(chunk)
272 else:
273 read_it = pool.pregenerate(total, chunk)
274 write_it = write.pregenerate(total, chunk)
275
276 for op_name, op_fn in [
277 ("read", lambda c: c.read(*next(read_it))),
278 ("write", lambda c: c.write(*next(write_it))),
279 ]:
280 lats, wall = await run(ctx, conc, TOTAL_OPS, op_fn, WARMUP_OPS)
281 s = calc_stats(lats, wall, chunk, TOTAL_OPS)
282 print(_row(name, op_name, pivot, 5, s), flush=True)
283 for lat in lats:
284 csv.append(
285 f"{name},{sweep_tag},{op_name},{conc},{chunk},"
286 f"{lat * 1e6:.1f},{s['wall_s']:.4f},{s['n_ops']}"
287 )
288
289 ctx.close()
290
291 return csv
292
293
294 async def sweep_chunk(
295 name: str, CtxCls, pool: ReadPool, write: WriteTarget,
296 access: str = "rand",
297 ) -> List[str]:
298 """Vary chunk size at fixed concurrency."""
299 csv: List[str] = []
300 conc = CHUNK_SWEEP_CONC
301 ctx = CtxCls(max_requests=MAX_REQUESTS)
302 total = TOTAL_OPS + WARMUP_OPS
303 sweep_tag = f"chunk_sweep_{access}"
304
305 for chunk in CHUNK_SWEEP_SIZES:
306 pivot = f"{chunk // 1024}K"
307 if access == "seq":
308 read_it = pool.pregenerate_seq(chunk)
309 write_it = write.pregenerate_seq(chunk)
310 else:
311 read_it = pool.pregenerate(total, chunk)
312 write_it = write.pregenerate(total, chunk)
313
314 for op_name, op_fn in [
315 ("read", lambda c: c.read(*next(read_it))),
316 ("write", lambda c: c.write(*next(write_it))),
317 ]:
318 lats, wall = await run(ctx, conc, TOTAL_OPS, op_fn, WARMUP_OPS)
319 s = calc_stats(lats, wall, chunk, TOTAL_OPS)
320 print(_row(name, op_name, pivot, 5, s), flush=True)
321 for lat in lats:
322 csv.append(
323 f"{name},{sweep_tag},{op_name},{conc},{chunk},"
324 f"{lat * 1e6:.1f},{s['wall_s']:.4f},{s['n_ops']}"
325 )
326
327 ctx.close()
328 return csv
329
330
331 # ── main ──────────────────────────────────────────────────────────────────────
332
333 async def main():
334 RESULTS_DIR.mkdir(parents=True, exist_ok=True)
335
336 pool = ReadPool()
337 pool.open()
338 write = WriteTarget()
339
340 available = []
341 for label, mod_name, cls_name in BACKENDS:
342 try:
343 m = importlib.import_module(mod_name)
344 available.append((label, getattr(m, cls_name)))
345 except ImportError as e:
346 print(f"skip {label}: {e}", file=sys.stderr)
347
348 if not available:
349 sys.exit("No backends available.")
350
351 CSV_HEADER = "backend,sweep,op,concurrency,chunk_bytes,latency_us,wall_s,n_ops\n"
352
353 per_backend: dict[str, List[str]] = {}
354 for name, Cls in available:
355 per_backend.setdefault(name, [])
356
357 def _run_sweep(title: str, hdr: str, coro_fn):
358 sep = "─" * len(hdr)
359 print(f"\n{'━'*len(hdr)}")
360 print(title)
361 print(hdr)
362 print(sep)
363 return sep
364
365 # ── sweep 1: concurrency, random ─────────────────────────────────────────
366 hdr1 = _hdr("conc", 5)
367 sep1 = _run_sweep(
368 f"SWEEP 1 — concurrency / random (chunk={CONC_SWEEP_CHUNK//1024} KB, ops={TOTAL_OPS})",
369 hdr1, None,
370 )
371 for name, Cls in available:
372 rows = await sweep_concurrency(name, Cls, pool, write, access="rand")
373 per_backend[name].extend(rows)
374 print(sep1)
375
376 # ── sweep 2: chunk size, random ───────────────────────────────────────────
377 hdr2 = _hdr("chunk", 5)
378 sep2 = _run_sweep(
379 f"SWEEP 2 — chunk size / random (concurrency={CHUNK_SWEEP_CONC}, ops={TOTAL_OPS})",
380 hdr2, None,
381 )
382 for name, Cls in available:
383 rows = await sweep_chunk(name, Cls, pool, write, access="rand")
384 per_backend[name].extend(rows)
385 print(sep2)
386
387 # ── sweep 3: concurrency, sequential ─────────────────────────────────────
388 sep3 = _run_sweep(
389 f"SWEEP 3 — concurrency / sequential (chunk={CONC_SWEEP_CHUNK//1024} KB, ops={TOTAL_OPS})",
390 hdr1, None,
391 )
392 for name, Cls in available:
393 rows = await sweep_concurrency(name, Cls, pool, write, access="seq")
394 per_backend[name].extend(rows)
395 print(sep3)
396
397 # ── sweep 4: chunk size, sequential ──────────────────────────────────────
398 sep4 = _run_sweep(
399 f"SWEEP 4 — chunk size / sequential (concurrency={CHUNK_SWEEP_CONC}, ops={TOTAL_OPS})",
400 hdr2, None,
401 )
402 for name, Cls in available:
403 rows = await sweep_chunk(name, Cls, pool, write, access="seq")
404 per_backend[name].extend(rows)
405 print(sep4)
406
407 # ── save CSVs — always one file per backend ───────────────────────────────
408 for name, rows in per_backend.items():
409 out = RESULTS_DIR / f"bench_{name}.csv"
410 out.write_text(CSV_HEADER + "\n".join(rows) + "\n")
411 print(f"CSV → {out}")
412
413 pool.close()
414 write.close()
415
416
417 if __name__ == "__main__":
418 import argparse
419
420 parser = argparse.ArgumentParser()
421 parser.add_argument(
422 "--backend",
423 choices=[b[0] for b in BACKENDS],
424 default=None,
425 help="Run a single backend (default: all)",
426 )
427 args = parser.parse_args()
428
429 if args.backend:
430 BACKENDS[:] = [b for b in BACKENDS if b[0] == args.backend]
431
432 asyncio.run(main())