Debian Codegraph @

benchmark/plot_results.py

raw
1 """
2 Plot and compare caio benchmark results with and without the GIL.
3
4 Produces figures saved to CAIO_RESULTS dir (once per access pattern: rand/seq):
5 concurrency_sweep_throughput_{rand,seq}.png
6 concurrency_sweep_latency_{rand,seq}.png
7 chunk_sweep_throughput_{rand,seq}.png
8 chunk_sweep_latency_{rand,seq}.png
9 latency_histograms.png (rand only)
10
11 Usage:
12 CAIO_RESULTS_GIL=/tmp/results-gil \
13 CAIO_RESULTS_NOGIL=/tmp/results-nogil \
14 PLOT_RESULTS=/tmp/results \
15 uv run --with matplotlib --with numpy python plot_results.py
16 """
17 import csv
18 import gzip
19 import os
20 import pathlib
21 from collections import defaultdict
22 from typing import Any
23
24 import matplotlib
25
26 matplotlib.use("Agg")
27 import matplotlib.pyplot as plt
28 import numpy as np
29 from matplotlib import ticker
30 from PIL import Image
31
32 SCRIPT_DIR = pathlib.Path(__file__).parent
33 RESULTS_DIR = SCRIPT_DIR / "results"
34 PLOT_RESULTS_DIR = pathlib.Path(os.environ.get("PLOT_RESULTS", RESULTS_DIR))
35 CSV_GIL_PATH = (
36 pathlib.Path(os.environ["CAIO_RESULTS_GIL"]) / "bench_all.csv"
37 if "CAIO_RESULTS_GIL" in os.environ
38 else RESULTS_DIR / "bench_all.csv.gz"
39 )
40 CSV_NOGIL_PATH = (
41 pathlib.Path(os.environ["CAIO_RESULTS_NOGIL"]) / "bench_all.csv"
42 if "CAIO_RESULTS_NOGIL" in os.environ
43 else RESULTS_DIR / "bench_all_nogil.csv.gz"
44 )
45
46 OUTPUT_SUFFIX = ""
47 MODE_LABEL = ""
48
49 BACKENDS = [
50 "linux_uring",
51 "linux_aio",
52 "thread_aio",
53 "python_aio",
54 ]
55
56 OP_COLORS = {"read": "#3498db", "write": "#e74c3c"}
57 OP_MARKERS = {"read": "o", "write": "s"}
58
59
60
61 # ── data loading ──────────────────────────────────────────────────────────────
62
63 Row = dict[str, str]
64
65 def load_csv(path: pathlib.Path) -> list[Row]:
66 if path.suffix == ".gz":
67 with gzip.open(path, mode="rt", newline="") as fp:
68 return list(csv.DictReader(fp))
69 with path.open(mode="r", newline="") as fp:
70 return list(csv.DictReader(fp))
71
72
73 def pct(values: list[float], p: float) -> float:
74 s = sorted(values)
75 return s[min(int(len(s) * p), len(s) - 1)]
76
77
78 CellData = dict[str, Any] # keys: lats (List[float]), wall_s (float), n_ops (int)
79
80
81 def group(
82 rows: list[Row],
83 sweep: str,
84 op: str,
85 ) -> defaultdict[str, defaultdict[int, CellData]]:
86 """Returns {backend: {pivot_value: {lats: [...], wall_s: float, n_ops: int}}}.
87
88 `sweep` is the full sweep tag, e.g. 'conc_sweep_rand' or 'chunk_sweep_seq'.
89 The pivot key is concurrency for conc sweeps, chunk_bytes for chunk sweeps.
90 """
91 is_conc = sweep.startswith("conc_sweep")
92 result: defaultdict[str, defaultdict[int, CellData]] = defaultdict(
93 lambda: defaultdict(lambda: {"lats": [], "wall_s": 0.0, "n_ops": 0}),
94 )
95 for r in rows:
96 if r["sweep"] != sweep or r["op"] != op:
97 continue
98 if not r.get("latency_us"):
99 continue
100 pivot = int(r["concurrency"] if is_conc else r["chunk_bytes"])
101 cell = result[r["backend"]][pivot]
102 cell["lats"].append(float(r["latency_us"]))
103 if r.get("wall_s"):
104 cell["wall_s"] = float(r["wall_s"])
105 if r.get("n_ops"):
106 cell["n_ops"] = int(r["n_ops"])
107 return result
108
109
110 # ── plot helpers ──────────────────────────────────────────────────────────────
111
112 def apply_style(ax, xlabel: str, ylabel: str, title: str,
113 xscale="linear", yscale="linear"):
114 ax.set_xlabel(xlabel, fontsize=10)
115 ax.set_ylabel(ylabel, fontsize=10)
116 ax.set_title(title, fontsize=11, fontweight="bold")
117 ax.set_xscale(xscale)
118 ax.set_yscale(yscale)
119 ax.grid(True, which="both", linestyle="--", alpha=0.4)
120 ax.spines["top"].set_visible(False)
121 ax.spines["right"].set_visible(False)
122
123
124 def _mode_title(title: str) -> str:
125 if not MODE_LABEL:
126 return title
127 return f"{title} — {MODE_LABEL}"
128
129
130 def _output_path(name: str) -> pathlib.Path:
131 stem, suffix = os.path.splitext(name)
132 return PLOT_RESULTS_DIR / f"{stem}{OUTPUT_SUFFIX}{suffix}"
133
134
135 def _percentile_footer(
136 ax,
137 rows: list[Row],
138 sweep: str,
139 backend: str,
140 ) -> None:
141 """Compact aggregate latency summary below every subplot."""
142 lines = []
143 for op in ("read", "write"):
144 values = [
145 float(row["latency_us"]) / 1000
146 for row in rows
147 if row["sweep"] == sweep
148 and row["backend"] == backend
149 and row["op"] == op
150 and row.get("latency_us")
151 ]
152 if not values:
153 continue
154 stats = " ".join(
155 f"p{int(quantile * 100)} {pct(values, quantile):.3f}"
156 for quantile in (0.25, 0.50, 0.95, 0.99)
157 )
158 lines.append(f"{op}: {stats} ms")
159
160 if lines:
161 ax.text(
162 0.5,
163 -0.30,
164 "\n".join(lines),
165 transform=ax.transAxes,
166 ha="center",
167 va="top",
168 fontsize=6.2,
169 color="#555555",
170 linespacing=1.35,
171 )
172
173
174 def _combine_mode_rows(
175 gil_path: pathlib.Path,
176 nogil_path: pathlib.Path,
177 output_path: pathlib.Path,
178 ) -> None:
179 """Stack GIL above no-GIL while preserving each row's exact layout."""
180 with Image.open(gil_path) as gil_image, Image.open(nogil_path) as nogil_image:
181 width = max(gil_image.width, nogil_image.width)
182 height = gil_image.height + nogil_image.height
183 combined = Image.new("RGB", (width, height), "white")
184 combined.paste(gil_image.convert("RGB"), (0, 0))
185 combined.paste(nogil_image.convert("RGB"), (0, gil_image.height))
186 combined.save(output_path)
187
188
189 def fmt_chunk(b: int) -> str:
190 if b >= 1024 * 1024:
191 return f"{b // (1024*1024)}M"
192 return f"{b // 1024}K"
193
194
195 def _op_legend(ax):
196 """Legend for read/write ops + band explanation."""
197 from matplotlib.lines import Line2D
198 from matplotlib.patches import Patch
199 elems = [
200 Line2D([0], [0], color=OP_COLORS[op], linewidth=2, marker=OP_MARKERS[op],
201 markersize=5, label=op)
202 for op in ("read", "write")
203 ] + [
204 Patch(facecolor="gray", alpha=0.25, label="p25–p75"),
205 Patch(facecolor="gray", alpha=0.10, label="p5–p95"),
206 ]
207 ax.legend(handles=elems, fontsize=7.5, framealpha=0.7)
208
209
210 def _chunk_xticks(ax, chunks: list[int]):
211 """Set numeric x-positions with human-readable tick labels."""
212 ax.set_xticks(range(len(chunks)))
213 ax.set_xticklabels([fmt_chunk(c) for c in chunks])
214
215
216 def _conc_xticks(ax, values: list[int]):
217 """Keep logarithmic concurrency labels readable in wide backend grids."""
218 ticks = values
219 if len(ticks) > 6:
220 ticks = ticks[::2]
221 if ticks[-1] != values[-1]:
222 ticks.append(values[-1])
223 ax.set_xticks(ticks)
224 ax.tick_params(axis="x", labelsize=8)
225
226
227 def _available(rows: list[Row]) -> list[str]:
228 """Backends that actually appear in the CSV data."""
229 present = {r["backend"] for r in rows}
230 return [b for b in BACKENDS if b in present]
231
232
233 # ── figure 1: concurrency sweep — throughput ──────────────────────────────────
234
235 def plot_conc_throughput(rows: list[Row], access: str = "rand"):
236 backends = _available(rows)
237 n = len(backends)
238 if not n:
239 return
240 fig, axes = plt.subplots(1, n, figsize=(4.5 * n, 5), sharey=True)
241 fig.suptitle(
242 _mode_title(
243 f"Throughput vs Concurrency (chunk=16 KB, {access})",
244 ),
245 fontsize=13,
246 fontweight="bold",
247 )
248 sweep = f"conc_sweep_{access}"
249 if n == 1:
250 axes = [axes]
251
252 for col, backend in enumerate(backends):
253 ax = axes[col]
254 xs_all: list[int] = []
255
256 for op in ("read", "write"):
257 data = group(rows, sweep, op)
258 if backend not in data:
259 continue
260 d = data[backend]
261 xs = sorted(d)
262 xs_all = xs
263 ys = []
264 for x in xs:
265 cell = d[x]
266 if cell["wall_s"] > 0 and cell["n_ops"] > 0:
267 ys.append(cell["n_ops"] / cell["wall_s"] / 1000)
268 else:
269 mean_s = np.mean(cell["lats"]) / 1e6
270 ys.append(x / mean_s / 1000 if mean_s > 0 else 0)
271
272 ax.plot(xs, ys, marker=OP_MARKERS[op], color=OP_COLORS[op],
273 label=op, linewidth=1.8, markersize=6)
274
275 apply_style(ax, "Concurrency", "kops/s", backend, xscale="log")
276 ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
277 _conc_xticks(ax, xs_all)
278 ax.legend(fontsize=8, framealpha=0.7)
279 _percentile_footer(ax, rows, sweep, backend)
280
281 fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
282 out = _output_path(f"concurrency_sweep_throughput_{access}.png")
283 fig.savefig(out, dpi=150, bbox_inches="tight")
284 print(f"saved {out}")
285 plt.close(fig)
286
287
288 # ── figure 2: concurrency sweep — latency ────────────────────────────────────
289
290 def plot_conc_latency(rows: list[Row], access: str = "rand"):
291 backends = _available(rows)
292 n = len(backends)
293 if not n:
294 return
295 fig, axes = plt.subplots(1, n, figsize=(4.5 * n, 5), sharey=True)
296 fig.suptitle(
297 _mode_title(f"Latency vs Concurrency (chunk=16 KB, {access})"),
298 fontsize=13,
299 fontweight="bold",
300 )
301 sweep = f"conc_sweep_{access}"
302 if n == 1:
303 axes = [axes]
304
305 for col, backend in enumerate(backends):
306 ax = axes[col]
307 pivots: list[int] = []
308
309 for op in ("read", "write"):
310 data = group(rows, sweep, op)
311 if backend not in data:
312 continue
313 d = data[backend]
314 pivots = sorted(d)
315 lats_list = [d[p]["lats"] for p in pivots]
316 xs = list(pivots)
317
318 p5s = [pct(l, 0.05) / 1000 for l in lats_list]
319 p25s = [pct(l, 0.25) / 1000 for l in lats_list]
320 p50s = [pct(l, 0.50) / 1000 for l in lats_list]
321 p75s = [pct(l, 0.75) / 1000 for l in lats_list]
322 p95s = [pct(l, 0.95) / 1000 for l in lats_list]
323
324 color = OP_COLORS[op]
325 ax.fill_between(xs, p5s, p95s, color=color, alpha=0.10)
326 ax.fill_between(xs, p25s, p75s, color=color, alpha=0.25)
327 ax.plot(xs, p50s, marker=OP_MARKERS[op], color=color,
328 label=op, linewidth=1.8, markersize=5)
329
330 apply_style(ax, "Concurrency", "Latency (ms)", backend,
331 xscale="log", yscale="log")
332 ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
333 if pivots:
334 _conc_xticks(ax, pivots)
335 _op_legend(ax)
336 _percentile_footer(ax, rows, sweep, backend)
337
338 fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
339 out = _output_path(f"concurrency_sweep_latency_{access}.png")
340 fig.savefig(out, dpi=150, bbox_inches="tight")
341 print(f"saved {out}")
342 plt.close(fig)
343
344
345 # ── figure 3: chunk sweep — throughput (MB/s) ─────────────────────────────────
346
347 def plot_chunk_throughput(rows: list[Row], access: str = "rand"):
348 backends = _available(rows)
349 n = len(backends)
350 if not n:
351 return
352 fig, axes = plt.subplots(1, n, figsize=(4.5 * n, 5), sharey=True)
353 fig.suptitle(
354 _mode_title(
355 f"Throughput vs Chunk Size (concurrency=64, {access})",
356 ),
357 fontsize=13,
358 fontweight="bold",
359 )
360 sweep = f"chunk_sweep_{access}"
361 if n == 1:
362 axes = [axes]
363
364 for col, backend in enumerate(backends):
365 ax = axes[col]
366 chunks: list[int] = []
367
368 for op in ("read", "write"):
369 data = group(rows, sweep, op)
370 if backend not in data:
371 continue
372 d = data[backend]
373 chunks = sorted(d)
374 xpos = list(range(len(chunks)))
375 ys = []
376 for chunk in chunks:
377 cell = d[chunk]
378 if cell["wall_s"] > 0 and cell["n_ops"] > 0:
379 ops_s = cell["n_ops"] / cell["wall_s"]
380 else:
381 mean_s = np.mean(cell["lats"]) / 1e6
382 ops_s = 64 / mean_s if mean_s > 0 else 0
383 ys.append(ops_s * chunk / 1e6) # MB/s
384
385 ax.plot(xpos, ys, marker=OP_MARKERS[op], color=OP_COLORS[op],
386 label=op, linewidth=1.8, markersize=6)
387
388 apply_style(ax, "Chunk size", "MB/s", backend)
389 _chunk_xticks(ax, chunks)
390 ax.legend(fontsize=8, framealpha=0.7)
391 _percentile_footer(ax, rows, sweep, backend)
392
393 fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
394 out = _output_path(f"chunk_sweep_throughput_{access}.png")
395 fig.savefig(out, dpi=150, bbox_inches="tight")
396 print(f"saved {out}")
397 plt.close(fig)
398
399
400 # ── figure 4: chunk sweep — latency ──────────────────────────────────────────
401
402 def plot_chunk_latency(rows: list[Row], access: str = "rand"):
403 backends = _available(rows)
404 n = len(backends)
405 if not n:
406 return
407 fig, axes = plt.subplots(1, n, figsize=(4.5 * n, 5), sharey=True)
408 fig.suptitle(
409 _mode_title(f"Latency vs Chunk Size (concurrency=64, {access})"),
410 fontsize=13,
411 fontweight="bold",
412 )
413 sweep = f"chunk_sweep_{access}"
414 if n == 1:
415 axes = [axes]
416
417 for col, backend in enumerate(backends):
418 ax = axes[col]
419 chunks: list[int] = []
420
421 for op in ("read", "write"):
422 data = group(rows, sweep, op)
423 if backend not in data:
424 continue
425 d = data[backend]
426 chunks = sorted(d)
427 xpos = list(range(len(chunks)))
428 lats_list = [d[c]["lats"] for c in chunks]
429
430 p5s = [pct(l, 0.05) / 1000 for l in lats_list]
431 p25s = [pct(l, 0.25) / 1000 for l in lats_list]
432 p50s = [pct(l, 0.50) / 1000 for l in lats_list]
433 p75s = [pct(l, 0.75) / 1000 for l in lats_list]
434 p95s = [pct(l, 0.95) / 1000 for l in lats_list]
435
436 color = OP_COLORS[op]
437 ax.fill_between(xpos, p5s, p95s, color=color, alpha=0.10)
438 ax.fill_between(xpos, p25s, p75s, color=color, alpha=0.25)
439 ax.plot(xpos, p50s, marker=OP_MARKERS[op], color=color,
440 label=op, linewidth=1.8, markersize=5)
441
442 apply_style(ax, "Chunk size", "Latency (ms)", backend, yscale="log")
443 _chunk_xticks(ax, chunks)
444 _op_legend(ax)
445 _percentile_footer(ax, rows, sweep, backend)
446
447 fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
448 out = _output_path(f"chunk_sweep_latency_{access}.png")
449 fig.savefig(out, dpi=150, bbox_inches="tight")
450 print(f"saved {out}")
451 plt.close(fig)
452
453
454 # ── figure 5: latency distribution histograms (concurrency=64, chunk=16K) ────
455
456 _HIST_COLORS = ["#3498db", "#e74c3c", "#2ecc71", "#f39c12", "#9b59b6"]
457
458
459 def plot_histograms(rows: list[Row]):
460 """Per-backend histogram of read latency at concurrency=64, chunk=16K."""
461 backends = _available(rows)
462 if not backends:
463 return
464 target_conc = 64
465
466 ncols = min(len(backends), 4)
467 nrows = (len(backends) + ncols - 1) // ncols
468 fig, axes = plt.subplots(nrows, ncols, figsize=(6.5 * ncols, 4.5 * nrows),
469 squeeze=False)
470 fig.suptitle(
471 _mode_title(
472 f"Read latency distribution "
473 f"(concurrency={target_conc}, chunk=16 KB)",
474 ),
475 fontsize=13, fontweight="bold",
476 )
477
478 for idx, backend in enumerate(backends):
479 ax = axes[idx // ncols][idx % ncols]
480 lats = [
481 float(r["latency_us"]) / 1000 # us -> ms
482 for r in rows
483 if r["sweep"] == "conc_sweep_rand"
484 and r["op"] == "read"
485 and r["backend"] == backend
486 and r.get("latency_us")
487 and int(r["concurrency"]) == target_conc
488 ]
489 if not lats:
490 ax.set_visible(False)
491 continue
492
493 p25 = pct(lats, 0.25)
494 p50 = pct(lats, 0.50)
495 p95 = pct(lats, 0.95)
496 p99 = pct(lats, 0.99)
497 clip = pct(lats, 0.999)
498
499 ax.hist(
500 [min(x, clip) for x in lats],
501 bins=80,
502 color=_HIST_COLORS[idx % len(_HIST_COLORS)],
503 alpha=0.75,
504 edgecolor="none",
505 )
506 for val, label, ls in [(p50, "p50", "-"), (p95, "p95", "--"), (p99, "p99", ":")]:
507 ax.axvline(val, color="black", linestyle=ls, linewidth=1.2,
508 label=f"{label}={val:.3f} ms")
509
510 ax.set_title(backend, fontweight="bold")
511 ax.set_xlabel("Latency (ms)")
512 ax.set_ylabel("Count")
513 ax.legend(fontsize=8)
514 ax.grid(True, linestyle="--", alpha=0.4)
515 ax.spines["top"].set_visible(False)
516 ax.spines["right"].set_visible(False)
517 ax.text(
518 0.5,
519 -0.24,
520 (
521 f"read: p25 {p25:.3f} p50 {p50:.3f} "
522 f"p95 {p95:.3f} p99 {p99:.3f} ms"
523 ),
524 transform=ax.transAxes,
525 ha="center",
526 va="top",
527 fontsize=6.5,
528 color="#555555",
529 )
530
531 # Hide unused subplot cells
532 for idx in range(len(backends), nrows * ncols):
533 axes[idx // ncols][idx % ncols].set_visible(False)
534
535 fig.tight_layout(rect=(0, 0.07, 1, 0.95), h_pad=3)
536 out = _output_path("latency_histograms.png")
537 fig.savefig(out, dpi=150, bbox_inches="tight")
538 print(f"saved {out}")
539 plt.close(fig)
540
541
542 # ── main ──────────────────────────────────────────────────────────────────────
543
544 def _render_mode(rows: list[Row], label: str, suffix: str) -> None:
545 global MODE_LABEL, OUTPUT_SUFFIX
546 MODE_LABEL = label
547 OUTPUT_SUFFIX = suffix
548 for access in ("rand", "seq"):
549 plot_conc_throughput(rows, access)
550 plot_conc_latency(rows, access)
551 plot_chunk_throughput(rows, access)
552 plot_chunk_latency(rows, access)
553 plot_histograms(rows)
554
555
556 def main():
557 missing = [
558 path for path in (CSV_GIL_PATH, CSV_NOGIL_PATH)
559 if not path.exists()
560 ]
561 if missing:
562 paths = "\n".join(str(path) for path in missing)
563 raise SystemExit(f"Benchmark CSV not found:\n{paths}")
564
565 PLOT_RESULTS_DIR.mkdir(parents=True, exist_ok=True)
566 gil_rows = load_csv(CSV_GIL_PATH)
567 nogil_rows = load_csv(CSV_NOGIL_PATH)
568 print(f"loaded {len(gil_rows):,} GIL rows from {CSV_GIL_PATH}")
569 print(f"loaded {len(nogil_rows):,} no-GIL rows from {CSV_NOGIL_PATH}")
570
571 _render_mode(gil_rows, "GIL", "_gil")
572 _render_mode(nogil_rows, "free-threaded / no GIL", "_nogil")
573
574 names = [
575 f"{prefix}_{access}.png"
576 for access in ("rand", "seq")
577 for prefix in (
578 "concurrency_sweep_throughput",
579 "concurrency_sweep_latency",
580 "chunk_sweep_throughput",
581 "chunk_sweep_latency",
582 )
583 ] + ["latency_histograms.png"]
584
585 for name in names:
586 stem, suffix = os.path.splitext(name)
587 gil_path = PLOT_RESULTS_DIR / f"{stem}_gil{suffix}"
588 nogil_path = PLOT_RESULTS_DIR / f"{stem}_nogil{suffix}"
589 output_path = PLOT_RESULTS_DIR / name
590 _combine_mode_rows(gil_path, nogil_path, output_path)
591 gil_path.unlink()
592 nogil_path.unlink()
593 print(f"combined {output_path}")
594
595 print(f"\nAll plots saved to {PLOT_RESULTS_DIR.resolve()}")
596
597
598 if __name__ == "__main__":
599 main()