-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgenerate-html.py
More file actions
1660 lines (1542 loc) · 50.5 KB
/
generate-html.py
File metadata and controls
1660 lines (1542 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Generate static HTML reports from dtoa-benchmark results.
Each ``results/*.json`` file (Google Benchmark's native JSON output) is
rendered to a self-contained ``.html`` file alongside it: server-rendered
SVG charts, no external dependencies, a tiny inline script for table
interactivity.
The JSON ``context`` block carries CPU info, caches, library version, and
custom keys such as ``commit_hash``/``machine``/``os``/``compiler``;
per-benchmark entries carry ``real_time``/``iterations``/counters.
Usage:
python3 generate-html.py results/foo.json [results/bar.json ...]
python3 generate-html.py --all
"""
from __future__ import annotations
import argparse
import hashlib
import html
import json
import math
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import Iterable
# Functions excluded from the bar chart because their times are large enough
# to flatten everyone else against the axis.
BAR_CHART_EXCLUDED = frozenset({"ostringstream", "sprintf"})
# Pseudo-method that does nothing; its time is the cost of the benchmark
# loop itself (data load, indirect call, buffer write). It's surfaced as a
# baseline footnote and a dashed reference line, not as a competing method.
BASELINE_METHOD = "null"
# Color palette for method series. Matches Google Charts' default
# palette (also what Google Sheets and the old chart used) so that
# previously published screenshots stay color-consistent.
PALETTE = [
"#3366cc", "#dc3912", "#ff9900", "#109618",
"#990099", "#0099c6", "#dd4477", "#66aa00",
"#b82e2e", "#316395", "#994499", "#22aa99",
"#aaaa11", "#6633cc", "#e67300", "#8b0707",
"#651067", "#329262", "#5574a6", "#3b3eac",
]
# Stable, name-keyed color assignments. The same method always renders in
# the same color, regardless of which result file it appears in or its
# position within ``benchmarks[]``. Slot indices reference ``PALETTE``;
# methods not listed here fall back to a deterministic hash-based slot
# (see ``_palette``), so future implementations stay consistent across
# runs without needing a code change.
METHOD_COLORS = {
# Top performers get the vivid, well-separated hues so they stay
# visually distinct in the line chart's "fast cluster".
"zmij": PALETTE[0], # #3366cc Google blue
"xjb64": PALETTE[1], # #dc3912 red
"fmt": PALETTE[2], # #ff9900 orange
"dragonbox": PALETTE[3], # #109618 green
"ryu": PALETTE[4], # #990099 purple
"to_chars": PALETTE[5], # #0099c6 cyan
"yy": PALETTE[6], # #dd4477 pink
"schubfach": PALETTE[11], # #22aa99 teal
"uscale": PALETTE[13], # #6633cc violet
# Mid / legacy methods get the deeper, more muted slots.
"double-conversion": PALETTE[9], # #316395 dark blue
"doubleconv": PALETTE[9], # legacy short name; same color
"milo": PALETTE[10], # #994499 dark purple
"grisu2": PALETTE[8], # #b82e2e dark red
"fpconv": PALETTE[12], # #aaaa11 olive
"gay": PALETTE[15], # #8b0707 deep red
"sprintf": PALETTE[14], # #e67300 dark orange
"ostringstream": PALETTE[7], # #66aa00 lime
"ostrstream": PALETTE[16], # #651067 deep purple
"null": PALETTE[17], # #329262 forest (baseline ref line)
# PALETTE[18] (#5574a6) and PALETTE[19] (#3b3eac) intentionally left
# free as natural slots for future implementations.
}
# ---------------------------------------------------------------------------
# Data loading
# ---------------------------------------------------------------------------
def load_json(path: Path) -> list[tuple[str, int, float]]:
"""Read Google Benchmark's native JSON output.
Each ``benchmarks[]`` entry has a name like ``method`` (mixed pool) or
``method/d<N>`` (per-digit). Ns-per-double comes from
``ns_per_double`` if present (written by migrate-csv-to-json.py for
legacy CSV imports), else the ``Time/double`` user counter that
``src/benchmark.cc`` always registers.
"""
with path.open() as f:
data = json.load(f)
rows: list[tuple[str, int, float]] = []
for r in data.get("benchmarks", []):
# Skip aggregate rows (mean/median/stddev) when --benchmark_repetitions
# is used; we want the raw per-iteration timings only.
if r.get("run_type") and r["run_type"] != "iteration":
continue
if r.get("error_occurred"):
continue
name = r.get("run_name") or r.get("name") or ""
sep = name.rfind("/d")
if sep == -1:
method, digit = name, 0
else:
method = name[:sep]
try:
digit = int(name[sep + 2:])
except ValueError:
continue
if "ns_per_double" in r:
time_ns = float(r["ns_per_double"])
elif "Time/double" in r:
time_ns = float(r["Time/double"]) * 1e9
else:
continue
rows.append((method, digit, time_ns))
return rows
def aggregate(rows: Iterable[tuple[str, int, float]]) -> dict:
"""Bucket rows by method. Returns ``methods``/``times``/``fixed``/
``digits``/``mean``. Mean matches the original PHP behaviour: if a
method has a row with digit==0 that single value is its mean,
otherwise the mean is ``sum(time for digit>0) / max_digit_global``.
"""
rows = list(rows)
methods: list[str] = []
times: dict[str, dict[int, float]] = defaultdict(dict)
fixed: dict[str, float] = {}
digits: set[int] = set()
max_digit = max((d for _, d, _ in rows), default=0)
for method, digit, time in rows:
if method not in times and method not in fixed:
methods.append(method)
if digit == 0:
fixed[method] = time
else:
times[method][digit] = time
digits.add(digit)
denom = max_digit or 1
mean: dict[str, float] = {}
for method in methods:
if method in fixed:
mean[method] = fixed[method]
else:
vals = times[method].values()
mean[method] = sum(vals) / denom if vals else 0.0
return {
"methods": methods,
"times": times,
"fixed": fixed,
"digits": sorted(digits),
"mean": mean,
}
# ---------------------------------------------------------------------------
# SVG rendering helpers
# ---------------------------------------------------------------------------
def _esc(s: str) -> str:
return html.escape(str(s), quote=True)
def _palette(methods: list[str]) -> dict[str, str]:
"""Stable, name-keyed color assignment. The same method always gets
the same color across result files (and across charts within a file).
Methods listed in ``METHOD_COLORS`` use their pinned color; unknown
methods fall back to a deterministic hash-based palette slot, so a
new implementation added later renders in the same color on every
machine without any code change.
"""
out: dict[str, str] = {}
for m in methods:
if m in METHOD_COLORS:
out[m] = METHOD_COLORS[m]
else:
digest = hashlib.md5(m.encode("utf-8")).digest()
out[m] = PALETTE[int.from_bytes(digest[:4], "big") % len(PALETTE)]
return out
def render_bar_chart(methods: list[str], means: dict[str, float],
colors: dict[str, str]) -> str:
items = [(m, means[m]) for m in methods if m not in BAR_CHART_EXCLUDED]
items.sort(key=lambda x: x[1])
n = len(items)
width = 820
label_w = 150
value_w = 80
bar_h = 26
gap = 10
pad_t = 10
pad_b = 10
plot_w = width - label_w - value_w - 16
height = pad_t + pad_b + n * bar_h + max(0, n - 1) * gap
max_v = max((v for _, v in items), default=1.0)
parts: list[str] = []
parts.append(
f'<svg viewBox="0 0 {width} {height}" '
f'class="chart bar-chart" role="img" '
f'aria-label="Mean conversion time per method">'
)
parts.append('<g class="bars">')
for i, (method, v) in enumerate(items):
y = pad_t + i * (bar_h + gap)
bw = (v / max_v) * plot_w if max_v > 0 else 0
color = colors[method]
parts.append(
f'<g class="bar" data-method="{_esc(method)}" data-value="{v:.4f}">'
)
# Transparent hit rect spanning the full row so the tooltip fires
# anywhere in the row, not only over the visible bar.
hit_y = y - gap / 2
hit_h = bar_h + gap
parts.append(
f'<rect class="hit" x="0" y="{hit_y:.2f}" width="{width}" '
f'height="{hit_h:.2f}" fill="transparent"/>'
)
parts.append(
f'<text x="{label_w - 10}" y="{y + bar_h / 2:.2f}" '
f'dominant-baseline="middle" text-anchor="end" class="lbl">'
f'{_esc(method)}</text>'
)
parts.append(
f'<rect class="fill" x="{label_w}" y="{y}" '
f'width="{bw:.2f}" height="{bar_h}" '
f'fill="{color}" rx="3" ry="3"/>'
)
parts.append(
f'<text x="{label_w + bw + 8:.2f}" y="{y + bar_h / 2:.2f}" '
f'dominant-baseline="middle" class="val">{v:,.2f} ns</text>'
)
parts.append('</g>')
parts.append('</g>')
parts.append('</svg>')
return f'<div class="chart-wrap bar-wrap">{"".join(parts)}</div>'
def _nice_log_ticks(vmin: float, vmax: float) -> tuple[float, float, list[float], list[float]]:
"""Return (log_lo, log_hi, major_ticks, minor_ticks) for a log-scale Y
axis. Majors land at 1*10^k and 5*10^k; minors at 2..4, 6..9 * 10^k.
The log range is padded slightly so the data lines don't touch the
plot edges."""
if vmin <= 0:
vmin = 1.0
if vmax <= vmin:
vmax = vmin * 10
log_lo = math.log10(vmin)
log_hi = math.log10(vmax)
span = log_hi - log_lo
pad = max(span * 0.04, 0.02)
log_lo -= pad
log_hi += pad
lo_dec = math.floor(log_lo)
hi_dec = math.ceil(log_hi)
majors: list[float] = []
minors: list[float] = []
for k in range(lo_dec, hi_dec + 1):
base = 10.0 ** k
for m in (1, 5):
v = m * base
if log_lo <= math.log10(v) <= log_hi:
majors.append(v)
for m in (2, 3, 4, 6, 7, 8, 9):
v = m * base
if log_lo <= math.log10(v) <= log_hi:
minors.append(v)
return log_lo, log_hi, majors, minors
def render_line_chart(methods: list[str], digits: list[int],
times: dict[str, dict[int, float]],
colors: dict[str, str],
baseline_method: str | None = None) -> str:
width, height = 820, 560
margin = {"l": 64, "r": 24, "t": 16, "b": 56}
plot_w = width - margin["l"] - margin["r"]
plot_h = height - margin["t"] - margin["b"]
# Reserve space at the bottom of the plot for a "0" baseline tick so
# the lines don't visually start from the chart's bottom edge.
zero_pad = 22
data_h = plot_h - zero_pad
all_vals = [v for m in methods for v in times[m].values() if v > 0]
# Include the loop-overhead baseline in the y-axis range so that its
# dashed reference line stays visible at the bottom of the plot.
if baseline_method and baseline_method in times:
all_vals += [v for v in times[baseline_method].values() if v > 0]
if not all_vals or not digits:
return '<svg viewBox="0 0 100 20" class="chart"></svg>'
vmin, vmax = min(all_vals), max(all_vals)
log_lo, log_hi, majors, minors = _nice_log_ticks(vmin, vmax)
def x_of(d: int) -> float:
if len(digits) == 1:
return margin["l"] + plot_w / 2
i = digits.index(d)
return margin["l"] + i * plot_w / (len(digits) - 1)
def y_of(t: float) -> float:
if t <= 0:
return margin["t"] + plot_h
v = (math.log10(t) - log_lo) / (log_hi - log_lo)
return margin["t"] + (1 - v) * data_h
y_zero = margin["t"] + plot_h
plot_left = margin["l"]
plot_right = margin["l"] + plot_w
plot_top = margin["t"]
plot_bot = margin["t"] + plot_h
parts: list[str] = []
parts.append(
f'<svg viewBox="0 0 {width} {height}" '
f'class="chart line-chart" role="img" '
f'aria-label="Time vs digit count, log scale">'
)
# Plot background
parts.append(
f'<rect x="{plot_left}" y="{plot_top}" '
f'width="{plot_w}" height="{plot_h}" class="plot-bg"/>'
)
# Vertical gridlines + X tick labels (one per digit)
for d in digits:
x = x_of(d)
parts.append(
f'<line x1="{x:.2f}" x2="{x:.2f}" '
f'y1="{plot_top}" y2="{plot_bot}" class="grid"/>'
)
parts.append(
f'<text x="{x:.2f}" y="{plot_bot + 18}" '
f'text-anchor="middle" class="ax">{d}</text>'
)
# Minor horizontal gridlines (log)
for v in minors:
y = y_of(v)
parts.append(
f'<line x1="{plot_left}" x2="{plot_right}" '
f'y1="{y:.2f}" y2="{y:.2f}" class="grid-minor"/>'
)
# Major horizontal gridlines + Y-axis labels
for v in majors:
y = y_of(v)
parts.append(
f'<line x1="{plot_left}" x2="{plot_right}" '
f'y1="{y:.2f}" y2="{y:.2f}" class="grid-major"/>'
)
parts.append(
f'<text x="{plot_left - 8}" y="{y:.2f}" '
f'dominant-baseline="middle" text-anchor="end" class="ax">'
f'{v:,g}</text>'
)
# "0" baseline at the bottom of the plot. The data lines never reach
# here (log scale can't represent zero), but the tick mirrors what
# Google Charts does and gives the chart a visual floor.
parts.append(
f'<line x1="{plot_left}" x2="{plot_right}" '
f'y1="{y_zero:.2f}" y2="{y_zero:.2f}" class="grid-major"/>'
)
parts.append(
f'<text x="{plot_left - 8}" y="{y_zero:.2f}" '
f'dominant-baseline="middle" text-anchor="end" class="ax">0</text>'
)
# Axis titles
parts.append(
f'<text x="{plot_left + plot_w / 2:.2f}" y="{height - 8}" '
f'text-anchor="middle" class="ax-title">Digits</text>'
)
parts.append(
f'<text transform="translate(16 {plot_top + plot_h / 2:.2f}) '
f'rotate(-90)" text-anchor="middle" class="ax-title">'
f'Time (ns)</text>'
)
# Series. Also collect per-point coordinates for JS hit-testing.
series_meta: list[dict] = []
parts.append('<g class="series">')
for method in methods:
pts = [(d, times[method].get(d, 0.0)) for d in digits
if times[method].get(d, 0.0) > 0]
if not pts:
continue
color = colors[method]
path = " ".join(f"{x_of(d):.2f},{y_of(t):.2f}" for d, t in pts)
parts.append(
f'<g class="ln" data-method="{_esc(method)}">'
f'<polyline points="{path}" fill="none" '
f'stroke="{color}" stroke-width="2" '
f'stroke-linejoin="round" stroke-linecap="round"/>'
f'</g>'
)
series_meta.append({
"method": method,
"color": color,
"points": [
{"d": d, "x": round(x_of(d), 2),
"y": round(y_of(t), 2), "v": t}
for d, t in pts
],
})
parts.append('</g>')
# Loop-overhead baseline as a dashed gray reference line. Not part of
# `series_meta`, so it's invisible to the tooltip / legend hit-testing.
if baseline_method and baseline_method in times:
bpts = [(d, times[baseline_method].get(d, 0.0)) for d in digits
if times[baseline_method].get(d, 0.0) > 0]
if bpts:
bpath = " ".join(f"{x_of(d):.2f},{y_of(t):.2f}" for d, t in bpts)
avg = sum(t for _, t in bpts) / len(bpts)
parts.append(
f'<g class="baseline">'
f'<polyline points="{bpath}" fill="none"/>'
f'<text x="{plot_right - 6}" y="{y_of(avg) - 6:.2f}" '
f'text-anchor="end" class="baseline-lbl">'
f'loop overhead ({avg:,.2f} ns)</text>'
f'</g>'
)
# Focus elements, revealed by JS on hover.
parts.append(
'<g class="focus" pointer-events="none" style="display:none">'
f'<line class="crosshair" y1="{plot_top}" y2="{plot_bot}"/>'
'<circle class="dot" r="4.5" fill="currentColor" stroke="white"'
' stroke-width="2"/>'
'</g>'
)
# Plot border
parts.append(
f'<rect x="{plot_left}" y="{plot_top}" '
f'width="{plot_w}" height="{plot_h}" class="plot-border"/>'
)
parts.append('</svg>')
meta = {
"width": width,
"height": height,
"plot": {"l": plot_left, "r": plot_right,
"t": plot_top, "b": plot_bot},
"series": series_meta,
}
# `<script>` content is raw text; escape any sequence that would close
# the tag prematurely. HTML entity escaping must NOT be applied here.
meta_json = (json.dumps(meta, separators=(",", ":"))
.replace("</", "<\\/"))
return (
'<div class="chart-wrap line-wrap">'
f'{"".join(parts)}'
f'<div class="tt" hidden></div>'
f'<script type="application/json" class="chart-meta">{meta_json}'
'</script>'
'</div>'
)
def render_legend(methods: list[str], colors: dict[str, str]) -> str:
items = []
for m in methods:
items.append(
f'<button type="button" class="lg" data-method="{_esc(m)}">'
f'<span class="sw" style="background:{colors[m]}"></span>{_esc(m)}'
f'</button>'
)
return f'<div class="legend">{"".join(items)}</div>'
def render_table(methods: list[str], means: dict[str, float]) -> str:
items = sorted(methods, key=lambda m: means[m])
body_rows = []
for m in items:
body_rows.append(
f'<tr data-method="{_esc(m)}" data-mean="{means[m]}" tabindex="0">'
f'<td class="f">{_esc(m)}</td>'
f'<td class="t num">{means[m]:,.2f}</td>'
f'<td class="s num"></td>'
f'</tr>'
)
return (
'<table class="results">'
'<thead><tr>'
'<th scope="col">Method</th>'
'<th scope="col" class="num">Time (ns)</th>'
'<th scope="col" class="num">Speedup</th>'
'</tr></thead>'
f'<tbody>{"".join(body_rows)}</tbody>'
'</table>'
)
# ---------------------------------------------------------------------------
# Page assembly
# ---------------------------------------------------------------------------
PAGE_CSS = """
:root {
--bg: #ffffff;
--bg-soft: #f6f7f9;
--fg: #0f172a;
--fg-muted: #64748b;
--border: #e2e8f0;
--border-strong: #cbd5e1;
--accent: #2563eb;
--accent-soft: #dbeafe;
--grid: #cccccc;
--grid-major: #b8bcc4;
--grid-minor: #e6e6e6;
--selected: #fef3c7;
--selected-fg: #78350f;
--shadow: 0 1px 2px rgba(15, 23, 42, 0.04),
0 4px 12px rgba(15, 23, 42, 0.04);
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b1220;
--bg-soft: #111a2e;
--fg: #e2e8f0;
--fg-muted: #94a3b8;
--border: #1e293b;
--border-strong: #334155;
--accent: #60a5fa;
--accent-soft: #1e3a8a;
--grid: #2f3641;
--grid-major: #44505f;
--grid-minor: #1a2230;
--selected: #422006;
--selected-fg: #fde68a;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.3),
0 4px 12px rgba(0, 0, 0, 0.25);
}
}
* { box-sizing: border-box; }
html { color-scheme: light dark; }
body {
margin: 0;
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
color: var(--fg);
background: var(--bg);
-webkit-font-smoothing: antialiased;
}
header.site {
position: sticky;
top: 0;
z-index: 10;
background: color-mix(in srgb, var(--bg) 92%, transparent);
backdrop-filter: saturate(160%) blur(8px);
border-bottom: 1px solid var(--border);
}
header.site .row {
max-width: 920px;
margin: 0 auto;
padding: 12px 24px;
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
header.site a.brand {
font-weight: 600;
color: var(--fg);
text-decoration: none;
}
header.site a.brand:hover { color: var(--accent); }
header.site nav {
display: flex;
gap: 8px;
align-items: center;
margin-left: auto;
flex-wrap: wrap;
}
header.site nav .nav-link {
padding: 6px 12px;
border: 1px solid var(--border-strong);
border-radius: 6px;
background: var(--bg-soft);
color: var(--fg);
text-decoration: none;
user-select: none;
transition: all 120ms ease;
}
header.site nav .nav-link:hover {
border-color: var(--accent);
color: var(--accent);
}
header.site nav .picker {
position: relative;
}
header.site nav .picker > summary {
list-style: none;
cursor: pointer;
padding: 6px 12px;
border: 1px solid var(--border-strong);
border-radius: 6px;
background: var(--bg-soft);
user-select: none;
}
header.site nav .picker > summary::-webkit-details-marker { display: none; }
header.site nav .picker > summary::after {
content: " ▾";
color: var(--fg-muted);
}
header.site nav .picker[open] > summary {
border-color: var(--accent);
}
header.site nav .picker .menu {
position: absolute;
right: 0;
top: calc(100% + 4px);
min-width: 320px;
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--border-strong);
border-radius: 8px;
box-shadow: var(--shadow);
padding: 4px;
}
header.site nav .picker .menu a {
display: block;
padding: 6px 10px;
border-radius: 4px;
color: var(--fg);
text-decoration: none;
white-space: nowrap;
font-family: var(--mono);
font-size: 13px;
}
header.site nav .picker .menu a:hover {
background: var(--accent-soft);
color: var(--accent);
}
header.site nav .picker .menu a.current {
background: var(--accent-soft);
color: var(--accent);
font-weight: 600;
}
main {
max-width: 920px;
margin: 0 auto;
padding: 24px;
}
h1 {
font-size: 22px;
margin: 8px 0 4px;
font-family: var(--mono);
word-break: break-all;
}
h3 {
font-size: 14px;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--fg-muted);
margin: 0 0 12px;
font-weight: 600;
}
.card {
background: var(--bg);
border: 1px solid var(--border);
border-radius: 10px;
padding: 20px;
margin-bottom: 16px;
box-shadow: var(--shadow);
}
.card .hint {
color: var(--fg-muted);
font-size: 12px;
margin: 8px 0 0;
}
.card .card-divider {
height: 1px;
background: var(--border);
margin: 24px -20px;
}
table.results {
width: 100%;
border-collapse: collapse;
font-variant-numeric: tabular-nums;
}
table.results th,
table.results td {
padding: 8px 12px;
border-bottom: 1px solid var(--border);
text-align: left;
}
table.results th {
font-weight: 600;
color: var(--fg-muted);
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
table.results td.num,
table.results th.num { text-align: right; }
table.results tbody tr {
cursor: pointer;
transition: background-color 80ms ease;
}
table.results tbody tr:hover { background: var(--bg-soft); }
table.results tbody tr.selected {
background: var(--selected);
color: var(--selected-fg);
}
table.results tbody tr.selected td.f { font-weight: 600; }
table.results tbody tr:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.chart-wrap {
position: relative;
}
.chart {
width: 100%;
height: auto;
display: block;
}
.chart .lbl,
.chart .val,
.chart .ax {
fill: var(--fg);
font-size: 12px;
font-family: var(--mono);
}
.chart .ax,
.chart .val { fill: var(--fg-muted); }
.chart .ax-title {
fill: var(--fg-muted);
font-size: 12px;
font-style: italic;
}
.line-chart .ax,
.line-chart .ax-title { fill: var(--fg); }
.chart .grid { stroke: var(--grid); stroke-width: 1; }
.chart .grid-major { stroke: var(--grid-major); stroke-width: 1; }
.chart .grid-minor { stroke: var(--grid-minor); stroke-width: 1; }
.chart .plot-bg { fill: var(--bg-soft); }
.line-chart .plot-bg { fill: var(--bg); }
.chart .plot-border {
fill: none;
stroke: var(--border-strong);
stroke-width: 1;
}
.bar-chart .bar .fill { transition: filter 120ms ease; }
.bar-chart .bar.focused .fill {
filter: drop-shadow(0 2px 4px rgba(15, 23, 42, 0.35));
}
@media (prefers-color-scheme: dark) {
.bar-chart .bar.focused .fill {
filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.75));
}
}
.line-chart .ln {
transition: opacity 120ms ease;
}
.line-chart.has-focus .ln { opacity: 0.2; }
.line-chart .ln.focused { opacity: 1; }
.line-chart .focus .crosshair {
stroke: var(--border-strong);
stroke-width: 1;
stroke-dasharray: 2 3;
}
.line-chart .baseline polyline {
fill: none;
stroke: var(--fg-muted);
stroke-width: 1.25;
stroke-dasharray: 6 4;
opacity: 0.55;
}
.line-chart .baseline-lbl {
fill: var(--fg-muted);
font-size: 11px;
font-style: italic;
font-family: var(--mono);
opacity: 0.85;
}
.tt {
position: absolute;
pointer-events: none;
background: var(--bg);
color: var(--fg);
border: 1px solid var(--border-strong);
border-radius: 6px;
padding: 8px 10px;
box-shadow: var(--shadow);
font-size: 12px;
line-height: 1.45;
white-space: nowrap;
z-index: 5;
transition: opacity 80ms ease;
}
.tt[hidden] { display: none; }
.tt .d {
font-weight: 700;
font-size: 13px;
margin-bottom: 2px;
color: var(--fg);
}
.tt .r {
display: flex;
align-items: center;
gap: 6px;
color: var(--fg-muted);
}
.tt .r .sw {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
flex: none;
}
.tt .r .f { color: var(--fg); }
.tt .r .v { color: var(--fg); font-weight: 600; }
.legend {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 12px;
}
.legend .lg {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--bg);
color: var(--fg);
font: inherit;
cursor: pointer;
transition: all 120ms ease;
}
.legend .lg:hover { border-color: var(--border-strong); }
.legend .lg.dim { opacity: 0.35; }
.legend .lg.active {
border-color: var(--accent);
background: var(--accent-soft);
}
.legend .sw {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
}
.hint-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
margin: 8px 0 0;
}
.hint-row .hint { margin: 0; }
.copy-md {
background: var(--bg);
color: var(--fg-muted);
border: 1px solid var(--border);
border-radius: 6px;
padding: 4px 10px;
font: inherit;
font-size: 12px;
cursor: pointer;
transition: all 120ms ease;
white-space: nowrap;
}
.copy-md:hover {
border-color: var(--border-strong);
color: var(--fg);
}
.copy-md.copied {
border-color: var(--accent);
color: var(--accent);
}
footer {
max-width: 920px;
margin: 32px auto 48px;
padding: 16px 24px;
color: var(--fg-muted);
font-size: 12px;
border-top: 1px solid var(--border);
}
footer a { color: inherit; }
"""
PAGE_JS = r"""
(function () {
// Table: click a row to make it the speedup baseline. The initial
// baseline is `sprintf` (or the first row), but we don't highlight it
// until the user actually picks one.
document.querySelectorAll("table.results").forEach(function (tbl) {
var rows = Array.prototype.slice.call(tbl.querySelectorAll("tbody tr"));
function recompute(baseRow, highlight) {
var base = parseFloat(baseRow.dataset.mean);
rows.forEach(function (r) {
var t = parseFloat(r.dataset.mean);
var ratio = t > 0 ? base / t : 0;
r.querySelector(".s").textContent = ratio.toFixed(3) + "x";
r.classList.toggle("selected", highlight && r === baseRow);
});
}
rows.forEach(function (r) {
r.addEventListener("click", function () { recompute(r, true); });
r.addEventListener("keydown", function (e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
recompute(r, true);
}
});
});
var defaultRow = rows.find(function (r) {
return r.dataset.method === "sprintf";
}) || rows[0];
if (defaultRow) recompute(defaultRow, false);
});
// Copy-as-Markdown button: serializes the adjacent results table to a
// GitHub-flavored markdown table with right-aligned numeric columns.
document.querySelectorAll(".copy-md").forEach(function (btn) {
btn.addEventListener("click", function () {
var card = btn.closest(".card");
var tbl = card && card.querySelector("table.results");
if (!tbl) return;
var ths = Array.prototype.slice.call(tbl.querySelectorAll("thead th"));
var heads = ths.map(function (th) { return th.textContent.trim(); });
var rights = ths.map(function (th) {
return th.classList.contains("num");
});
var rows = Array.prototype.slice.call(
tbl.querySelectorAll("tbody tr")
).map(function (tr) {
return Array.prototype.slice.call(tr.cells).map(function (td) {
return td.textContent.trim();
});
});
var widths = heads.map(function (h, i) {
var w = h.length;
rows.forEach(function (r) {
if (r[i] && r[i].length > w) w = r[i].length;
});
return w;
});
function pad(s, w, right) {
while (s.length < w) s = right ? " " + s : s + " ";
return s;
}
function fmtRow(cells) {
return "| " + cells.map(function (c, i) {
return pad(c, widths[i], rights[i]);
}).join(" | ") + " |";
}
var sep = "|" + widths.map(function (w, i) {
var len = w + 2;
return rights[i]
? new Array(len).join("-") + ":"
: new Array(len + 1).join("-");
}).join("|") + "|";
var md = [fmtRow(heads), sep]
.concat(rows.map(fmtRow)).join("\n") + "\n";
function done(ok) {
var orig = btn.dataset.label || btn.textContent;
btn.dataset.label = orig;
btn.textContent = ok ? "Copied!" : "Copy failed";
btn.classList.toggle("copied", ok);
setTimeout(function () {
btn.textContent = orig;
btn.classList.remove("copied");
}, 1500);
}
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(md).then(
function () { done(true); },
function () { done(false); }
);
} else {
// Fallback for non-secure contexts (e.g. file:// + old browsers).