Debian Codegraph @

bench/cmd/mktables/main.go

raw
1 // mktables - regenerate markdown benchmark tables from raw results files.
2 //
3 // Usage:
4 //
5 // go run ./cmd/mktables -synth results/synthetic.txt -trace results/trace.txt
6 //
7 // Parses `go test -bench` output (synthetic: count=N, medians reported) and
8 // the -v trace run (miss-ratio test logs, replay/parallel benchmarks,
9 // GC-pressure logs), then emits the markdown tables used in bench-results.md,
10 // README.md, and bench/README.md. Derived claims (e.g. "k=1 beats LRU on
11 // N of M traces") are computed here — never count them by hand.
12 package main
13
14 import (
15 "bufio"
16 "flag"
17 "fmt"
18 "os"
19 "regexp"
20 "sort"
21 "strconv"
22 "strings"
23 )
24
25 // sample is one benchmark line's metrics, keyed by unit ("ns/op", "B/op", ...).
26 type sample map[string]float64
27
28 // benchData accumulates samples per benchmark name (count>1 → multiple).
29 type benchData map[string][]sample
30
31 // -N GOMAXPROCS suffix is absent when GOMAXPROCS=1 (sweep runs).
32 var benchLine = regexp.MustCompile(`^Benchmark(\S+?)(?:-\d+)?\s+(\d+)\s+(.*)$`)
33
34 func parseBenchFile(path string, into benchData) error {
35 f, err := os.Open(path)
36 if err != nil {
37 return err
38 }
39 defer f.Close()
40
41 sc := bufio.NewScanner(f)
42 sc.Buffer(make([]byte, 1024*1024), 1024*1024)
43 for sc.Scan() {
44 m := benchLine.FindStringSubmatch(sc.Text())
45 if m == nil {
46 continue
47 }
48 name := m[1]
49 s := sample{}
50 fields := strings.Fields(m[3])
51 for i := 0; i+1 < len(fields); i += 2 {
52 v, err := strconv.ParseFloat(fields[i], 64)
53 if err != nil {
54 continue
55 }
56 s[fields[i+1]] = v
57 }
58 into[name] = append(into[name], s)
59 }
60 return sc.Err()
61 }
62
63 // median of metric u across all samples of benchmark name; NaN-free: returns
64 // (0, false) when absent.
65 func (b benchData) median(name, u string) (float64, bool) {
66 var vals []float64
67 for _, s := range b[name] {
68 if v, ok := s[u]; ok {
69 vals = append(vals, v)
70 }
71 }
72 if len(vals) == 0 {
73 return 0, false
74 }
75 sort.Float64s(vals)
76 return vals[len(vals)/2], true
77 }
78
79 func fmtNs(v float64, ok bool) string {
80 if !ok {
81 return "—"
82 }
83 switch {
84 case v >= 1e6:
85 return fmt.Sprintf("%.2f ms", v/1e6)
86 case v >= 10_000:
87 return fmt.Sprintf("%.1f µs", v/1000)
88 case v >= 100:
89 return fmt.Sprintf("%.1f", v)
90 default:
91 return fmt.Sprintf("%.2f", v)
92 }
93 }
94
95 // --- trace -v log parsing -------------------------------------------------
96
97 var (
98 runLine = regexp.MustCompile(`^=== (?:RUN|CONT)\s+(\S+)`)
99 missLine = regexp.MustCompile(`^\s+replay_test\.go:\d+:\s+(sieve-k1|sieve-k2|sieve-k3|LRU|ARC)\s+miss ratio: ([0-9.]+)`)
100 gcLine = regexp.MustCompile(`^\s+replay_test\.go:\d+:\s+(sieve-k1|sieve-k3|LRU|ARC)\s+(\d+)\s+(\d+) us\s+(\d+) KB\s+(\d+)$`)
101 gcTrcLine = regexp.MustCompile(`^\s+replay_test\.go:\d+:\s+Using trace: (\S+)`)
102 )
103
104 type traceLogs struct {
105 missRatio map[string]map[string]float64 // trace -> variant -> ratio
106 gcTrace string
107 gcRows [][]string // variant, numGC, pause us, alloc KB, heap objs
108 traces []string // insertion order
109 }
110
111 func parseTraceLogs(path string) (*traceLogs, error) {
112 f, err := os.Open(path)
113 if err != nil {
114 return nil, err
115 }
116 defer f.Close()
117
118 tl := &traceLogs{missRatio: map[string]map[string]float64{}}
119 cur := ""
120 sc := bufio.NewScanner(f)
121 sc.Buffer(make([]byte, 1024*1024), 1024*1024)
122 for sc.Scan() {
123 line := sc.Text()
124 if m := runLine.FindStringSubmatch(line); m != nil {
125 cur = m[1]
126 continue
127 }
128 if m := missLine.FindStringSubmatch(line); m != nil {
129 name := strings.TrimPrefix(cur, "TestMissRatio/")
130 if name == cur || name == "" {
131 continue // miss-ratio log outside a TestMissRatio subtest
132 }
133 if tl.missRatio[name] == nil {
134 tl.missRatio[name] = map[string]float64{}
135 tl.traces = append(tl.traces, name)
136 }
137 v, _ := strconv.ParseFloat(m[2], 64)
138 tl.missRatio[name][m[1]] = v
139 continue
140 }
141 if m := gcTrcLine.FindStringSubmatch(line); m != nil {
142 tl.gcTrace = m[1]
143 continue
144 }
145 if m := gcLine.FindStringSubmatch(line); m != nil {
146 tl.gcRows = append(tl.gcRows, m[1:])
147 }
148 }
149 return tl, sc.Err()
150 }
151
152 // --- table emitters --------------------------------------------------------
153
154 var missVariants = []string{"sieve-k1", "sieve-k2", "sieve-k3", "LRU", "ARC"}
155
156 func emitMissRatio(tl *traceLogs) {
157 fmt.Println("### Miss ratio (every trace)")
158 fmt.Println()
159 fmt.Println("Cache sized at 10% of unique keys. **Bold** = best in row.")
160 fmt.Println()
161 fmt.Println("| Trace | SIEVE k=1 | SIEVE k=2 | SIEVE k=3 | LRU | ARC |")
162 fmt.Println("|-------|----------:|----------:|----------:|----:|----:|")
163
164 bestCount := map[string]int{}
165 k1Wins, lruWins, ties := 0, 0, 0
166 traces := append([]string(nil), tl.traces...)
167 sort.Strings(traces)
168 for _, tr := range traces {
169 row := tl.missRatio[tr]
170 best := ""
171 for _, v := range missVariants {
172 if best == "" || row[v] < row[best] {
173 best = v
174 }
175 }
176 bestCount[best]++
177 switch {
178 case row["sieve-k1"] < row["LRU"]:
179 k1Wins++
180 case row["LRU"] < row["sieve-k1"]:
181 lruWins++
182 default:
183 ties++
184 }
185 fmt.Printf("| %s |", tr)
186 for _, v := range missVariants {
187 cell := fmt.Sprintf("%.4f", row[v])
188 if v == best {
189 cell = "**" + cell + "**"
190 }
191 fmt.Printf(" %s |", cell)
192 }
193 fmt.Println()
194 }
195 fmt.Println()
196 fmt.Printf("Derived (computed by mktables, n=%d traces):\n", len(traces))
197 fmt.Printf("- Best-in-row counts: ")
198 var parts []string
199 for _, v := range missVariants {
200 if bestCount[v] > 0 {
201 parts = append(parts, fmt.Sprintf("%s: %d", v, bestCount[v]))
202 }
203 }
204 fmt.Println(strings.Join(parts, ", "))
205 fmt.Printf("- Head-to-head SIEVE k=1 vs LRU: k=1 lower on %d, LRU lower on %d, tied on %d\n",
206 k1Wins, lruWins, ties)
207 fmt.Println()
208 }
209
210 var traceVariants = []string{"SieveK1", "SieveK3", "LRU", "ARC"}
211
212 func emitTraceBench(bd benchData, prefix, title, note string) {
213 // Collect trace names present under this prefix.
214 set := map[string]bool{}
215 for name := range bd {
216 if !strings.HasPrefix(name, prefix+"/") {
217 continue
218 }
219 rest := strings.TrimPrefix(name, prefix+"/")
220 i := strings.LastIndex(rest, "/")
221 if i < 0 {
222 continue
223 }
224 set[rest[:i]] = true
225 }
226 if len(set) == 0 {
227 return
228 }
229 var traces []string
230 for t := range set {
231 traces = append(traces, t)
232 }
233 // Sort by SieveK1 ns/op ascending, like the README tables.
234 sort.Slice(traces, func(a, b int) bool {
235 va, _ := bd.median(prefix+"/"+traces[a]+"/SieveK1", "ns/op")
236 vb, _ := bd.median(prefix+"/"+traces[b]+"/SieveK1", "ns/op")
237 return va < vb
238 })
239
240 fmt.Printf("### %s\n\n", title)
241 if note != "" {
242 fmt.Println(note)
243 fmt.Println()
244 }
245 fmt.Println("| Trace | SIEVE k=1 | SIEVE k=3 | LRU | ARC |")
246 fmt.Println("|-------|---------:|---------:|----:|----:|")
247 for _, tr := range traces {
248 fmt.Printf("| %s |", tr)
249 for i, v := range traceVariants {
250 val, ok := bd.median(prefix+"/"+tr+"/"+v, "ns/op")
251 cell := fmtNs(val, ok)
252 if i == 0 {
253 cell = "**" + cell + "**"
254 }
255 fmt.Printf(" %s |", cell)
256 }
257 fmt.Println()
258 }
259 fmt.Println()
260 }
261
262 func emitGCPressure(tl *traceLogs) {
263 if len(tl.gcRows) == 0 {
264 return
265 }
266 fmt.Printf("### GC pressure during replay (trace: %s)\n\n", tl.gcTrace)
267 fmt.Println("| Variant | NumGC | PauseTotal (µs) | TotalAlloc (KB) | HeapObjects |")
268 fmt.Println("|---------|------:|----------------:|----------------:|------------:|")
269 for _, r := range tl.gcRows {
270 fmt.Printf("| %s | %s | %s | %s | %s |\n", r[0], r[1], r[2], r[3], r[4])
271 }
272 fmt.Println()
273 }
274
275 type synthRow struct {
276 label string // display label
277 base string // benchmark name up to the variant segment
278 }
279
280 func emitSynth(bd benchData) {
281 rows := []synthRow{
282 {"`Get_Parallel`", "Get_Parallel"},
283 {"`Add_Parallel`", "Add_Parallel"},
284 {"`Probe_Parallel`", "Probe_Parallel"},
285 {"`Delete_Parallel`", "Delete_Parallel"},
286 {"`Mixed_Parallel` (60/30/10)", "Mixed_Parallel"},
287 {"`Zipf_Get_Parallel` (s=1.01)", "Zipf_Get_Parallel/s=1.01"},
288 {"`Zipf_Get_Parallel` (s=1.20)", "Zipf_Get_Parallel/s=1.20"},
289 {"`Zipf_Get_Parallel` (s=1.50)", "Zipf_Get_Parallel/s=1.50"},
290 }
291 fmt.Println("### Synthetic parallel micro-benchmarks (medians)")
292 fmt.Println()
293 fmt.Println("| Benchmark | Sieve | LRU | ARC |")
294 fmt.Println("|-----------|-------|-----|-----|")
295 for _, r := range rows {
296 fmt.Printf("| %s |", r.label)
297 for _, v := range []string{"Sieve", "LRU", "ARC"} {
298 ns, ok := bd.median(r.base+"/"+v, "ns/op")
299 if !ok {
300 fmt.Printf(" — |")
301 continue
302 }
303 cell := fmtNs(ns, ok) + " ns/op"
304 if b, ok2 := bd.median(r.base+"/"+v, "B/op"); ok2 {
305 cell += fmt.Sprintf(", %.0f B", b)
306 }
307 fmt.Printf(" %s |", cell)
308 }
309 fmt.Println()
310 }
311 fmt.Println()
312
313 // Memory footprint + GC impact, if present.
314 fmt.Println("### Memory footprint at fill (median heap-bytes)")
315 fmt.Println()
316 fmt.Println("| Entries | Sieve | LRU | ARC |")
317 fmt.Println("|---------|------:|----:|----:|")
318 for _, size := range []string{"100K", "500K", "1M"} {
319 fmt.Printf("| %s |", size)
320 for _, v := range []string{"Sieve", "LRU", "ARC"} {
321 hb, ok := bd.median("MemoryFootprint/"+size+"/"+v, "heap-bytes")
322 if !ok {
323 fmt.Printf(" — |")
324 continue
325 }
326 fmt.Printf(" %.1f MB |", hb/(1<<20))
327 }
328 fmt.Println()
329 }
330 fmt.Println()
331
332 fmt.Println("### GC impact at 1M entries (median)")
333 fmt.Println()
334 fmt.Println("| Variant | wall/iter | avg GC pause |")
335 fmt.Println("|---------|----------:|-------------:|")
336 for _, v := range []string{"Sieve", "LRU", "ARC"} {
337 ns, ok1 := bd.median("GCImpact/"+v, "ns/op")
338 p, ok2 := bd.median("GCImpact/"+v, "avg-gc-pause-ns")
339 if !ok1 && !ok2 {
340 continue
341 }
342 fmt.Printf("| %s | %s | %s |\n", v, fmtNs(ns, ok1), fmtNs(p, ok2))
343 }
344 fmt.Println()
345 }
346
347 func emitHeadlines(bd benchData) {
348 fmt.Println("### Headlines (computed)")
349 fmt.Println()
350
351 // Per-trace speedup: min(LRU, ARC) / SieveK1 for each trace under a
352 // prefix; report the min..max of those per-row ratios. Cross-trace
353 // lo/hi ratios would overstate the spread.
354 type span struct{ lo, hi float64 }
355 rowRatios := func(prefix string) (sieve, ratio span, n int) {
356 sieve.lo, ratio.lo = -1, -1
357 for name := range bd {
358 if !strings.HasPrefix(name, prefix+"/") || !strings.HasSuffix(name, "/SieveK1") {
359 continue
360 }
361 tr := strings.TrimSuffix(strings.TrimPrefix(name, prefix+"/"), "/SieveK1")
362 s, ok := bd.median(name, "ns/op")
363 if !ok || s == 0 {
364 continue
365 }
366 l, okL := bd.median(prefix+"/"+tr+"/LRU", "ns/op")
367 a, okA := bd.median(prefix+"/"+tr+"/ARC", "ns/op")
368 if !okL && !okA {
369 continue
370 }
371 best := l
372 if !okL || (okA && a < l) {
373 best = a
374 }
375 r := best / s
376 if sieve.lo < 0 || s < sieve.lo {
377 sieve.lo = s
378 }
379 if s > sieve.hi {
380 sieve.hi = s
381 }
382 if ratio.lo < 0 || r < ratio.lo {
383 ratio.lo = r
384 }
385 if r > ratio.hi {
386 ratio.hi = r
387 }
388 n++
389 }
390 return sieve, ratio, n
391 }
392 if s, r, n := rowRatios("ParallelGet"); n > 0 {
393 fmt.Printf("- Warm parallel Get (SIEVE k=1): %.2f–%.2f ns/op across %d traces; %.0fx–%.0fx faster than the better of LRU/ARC per trace\n",
394 s.lo, s.hi, n, r.lo, r.hi)
395 }
396 if s, r, n := rowRatios("ParallelReplay"); n > 0 {
397 fmt.Printf("- Cold parallel replay (SIEVE k=1): %.1f–%.1f ns/op across %d traces; %.1fx–%.1fx faster than the better of LRU/ARC per trace\n",
398 s.lo, s.hi, n, r.lo, r.hi)
399 }
400 fmt.Println()
401 }
402
403 // --- sweep parsing ----------------------------------------------------------
404
405 var sweepHdr = regexp.MustCompile(`^=== GOMAXPROCS=(\d+) ===$`)
406
407 // emitSweep parses a sweep file (sections per GOMAXPROCS) and emits a
408 // scaling table for the given benchmark bases.
409 func emitSweep(path string) error {
410 f, err := os.Open(path)
411 if err != nil {
412 return err
413 }
414 defer f.Close()
415
416 perProc := map[int]benchData{}
417 var procs []int
418 cur := -1
419 sc := bufio.NewScanner(f)
420 sc.Buffer(make([]byte, 1024*1024), 1024*1024)
421 for sc.Scan() {
422 line := sc.Text()
423 if m := sweepHdr.FindStringSubmatch(line); m != nil {
424 cur, _ = strconv.Atoi(m[1])
425 if perProc[cur] == nil {
426 perProc[cur] = benchData{}
427 procs = append(procs, cur)
428 }
429 continue
430 }
431 if cur < 0 {
432 continue
433 }
434 if m := benchLine.FindStringSubmatch(line); m != nil {
435 s := sample{}
436 fields := strings.Fields(m[3])
437 for i := 0; i+1 < len(fields); i += 2 {
438 if v, err := strconv.ParseFloat(fields[i], 64); err == nil {
439 s[fields[i+1]] = v
440 }
441 }
442 perProc[cur][m[1]] = append(perProc[cur][m[1]], s)
443 }
444 }
445 if err := sc.Err(); err != nil {
446 return err
447 }
448 sort.Ints(procs)
449
450 for _, base := range []string{"Get_Parallel", "Mixed_Parallel", "Zipf_Get_Parallel/s=1.01"} {
451 fmt.Printf("### Core scaling: %s (median ns/op)\n\n", base)
452 fmt.Println("| GOMAXPROCS | Sieve | LRU | ARC |")
453 fmt.Println("|-----------:|------:|----:|----:|")
454 for _, p := range procs {
455 fmt.Printf("| %d |", p)
456 for _, v := range []string{"Sieve", "LRU", "ARC"} {
457 val, ok := perProc[p].median(base+"/"+v, "ns/op")
458 fmt.Printf(" %s |", fmtNs(val, ok))
459 }
460 fmt.Println()
461 }
462 fmt.Println()
463 }
464 return nil
465 }
466
467 func main() {
468 synth := flag.String("synth", "", "synthetic results file (results/synthetic.txt)")
469 trace := flag.String("trace", "", "trace results file (results/trace.txt)")
470 sweep := flag.String("sweep", "", "core-scaling sweep file (results/sweep.txt)")
471 flag.Parse()
472
473 bd := benchData{}
474 var tl *traceLogs
475
476 if *synth != "" {
477 if err := parseBenchFile(*synth, bd); err != nil {
478 fmt.Fprintf(os.Stderr, "mktables: %v\n", err)
479 os.Exit(1)
480 }
481 }
482 if *trace != "" {
483 if err := parseBenchFile(*trace, bd); err != nil {
484 fmt.Fprintf(os.Stderr, "mktables: %v\n", err)
485 os.Exit(1)
486 }
487 var err error
488 if tl, err = parseTraceLogs(*trace); err != nil {
489 fmt.Fprintf(os.Stderr, "mktables: %v\n", err)
490 os.Exit(1)
491 }
492 }
493
494 if tl != nil {
495 emitTraceBench(bd, "ParallelGet",
496 "Parallel Get throughput (warm cache, ns/op)",
497 "Cache pre-warmed with a full replay; goroutines start at staggered trace offsets.")
498 emitTraceBench(bd, "ParallelReplay",
499 "Parallel Replay throughput (cold cache, mixed read+write, ns/op)",
500 "Probe() for SIEVE, Get+Add for LRU/ARC; no warmup; staggered trace offsets.")
501 emitTraceBench(bd, "Replay",
502 "Sequential replay (full trace per iteration, wall time)", "")
503 emitMissRatio(tl)
504 emitGCPressure(tl)
505 }
506 if *synth != "" {
507 emitSynth(bd)
508 }
509 if *sweep != "" {
510 if err := emitSweep(*sweep); err != nil {
511 fmt.Fprintf(os.Stderr, "mktables: %v\n", err)
512 os.Exit(1)
513 }
514 }
515 if tl != nil {
516 emitHeadlines(bd)
517 }
518 }