|
| 1 | +""" |
| 2 | +bench_ryu.py - Benchmark float-to-string conversion: Ryu vs Gay's dtoa |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python bench_ryu.py # run all benchmarks, print table |
| 6 | + python bench_ryu.py --json # emit JSON for comparison scripts |
| 7 | +
|
| 8 | +Cases covered: |
| 9 | + repr / str - shortest round-trip (mode 0, d2s) |
| 10 | + %e format - exponential N-significant-digit (mode 2, d2exp) |
| 11 | + %f format - fixed-point N-past-decimal (mode 3, d2fixed) |
| 12 | + %g format - general (mode 2, d2exp) |
| 13 | + f-string - f'{x:.3f}', f'{x:.6g}', f'{x!r}' |
| 14 | + float.__round__ - round(x, k) for k >= 0 and k < 0 |
| 15 | +""" |
| 16 | + |
| 17 | +import timeit |
| 18 | +import json |
| 19 | +import sys |
| 20 | +import math |
| 21 | + |
| 22 | +# --------------------------------------------------------------------------- |
| 23 | +# Test values |
| 24 | +# --------------------------------------------------------------------------- |
| 25 | + |
| 26 | +SMALL_INTS = [float(n) for n in range(1, 21)] |
| 27 | +FRACTIONS = [1.1, 1.23456789, 0.1, 0.001, 1/3, math.pi, math.e] |
| 28 | +LARGE = [1e100, 1.23456789e200, 9.9e307] |
| 29 | +SUBNORMALS = [5e-324, 2.2e-308, 1e-310] |
| 30 | +SPECIALS = [float('inf'), float('-inf'), float('nan')] |
| 31 | +NEGATIVES = [-1.5, -0.1, -math.pi] |
| 32 | +MIX = SMALL_INTS + FRACTIONS + LARGE + SUBNORMALS + NEGATIVES |
| 33 | + |
| 34 | + |
| 35 | +def _make_list(values, n=1000): |
| 36 | + """Repeat values to fill a list of length n.""" |
| 37 | + base = values * (n // len(values) + 1) |
| 38 | + return base[:n] |
| 39 | + |
| 40 | + |
| 41 | +# --------------------------------------------------------------------------- |
| 42 | +# Benchmark cases (name, stmt, setup) |
| 43 | +# --------------------------------------------------------------------------- |
| 44 | + |
| 45 | +def _build_cases(): |
| 46 | + cases = [] |
| 47 | + |
| 48 | + def add(name, stmt, values=None): |
| 49 | + if values is None: |
| 50 | + values = MIX |
| 51 | + lst = _make_list(values) |
| 52 | + # Use struct.unpack to reconstruct floats reliably (avoids inf/nan literal issues) |
| 53 | + import struct |
| 54 | + packed = struct.pack(f"{len(lst)}d", *lst) |
| 55 | + setup = ( |
| 56 | + f"import struct; " |
| 57 | + f"data = list(struct.unpack('{len(lst)}d', {packed!r}))" |
| 58 | + ) |
| 59 | + cases.append((name, stmt, setup)) |
| 60 | + |
| 61 | + # repr / str – mode 0 |
| 62 | + add("repr(x) [shortest]", |
| 63 | + "for x in data: repr(x)") |
| 64 | + add("str(x) [shortest]", |
| 65 | + "for x in data: str(x)") |
| 66 | + |
| 67 | + # %e – mode 2, exponential |
| 68 | + add("'%.6e' % x", |
| 69 | + "for x in data: '%.6e' % x") |
| 70 | + add("'%.2e' % x", |
| 71 | + "for x in data: '%.2e' % x", |
| 72 | + values=FRACTIONS + LARGE) |
| 73 | + |
| 74 | + # %f – mode 3 |
| 75 | + add("'%.3f' % x", |
| 76 | + "for x in data: '%.3f' % x") |
| 77 | + add("'%.6f' % x", |
| 78 | + "for x in data: '%.6f' % x") |
| 79 | + add("'%.10f' % x", |
| 80 | + "for x in data: '%.10f' % x", |
| 81 | + values=FRACTIONS) |
| 82 | + |
| 83 | + # %g – mode 2 (general) |
| 84 | + add("'%g' % x", |
| 85 | + "for x in data: '%g' % x") |
| 86 | + add("'%.4g' % x", |
| 87 | + "for x in data: '%.4g' % x") |
| 88 | + |
| 89 | + # f-strings (go through the same code paths as % formatting) |
| 90 | + add("f'{x:.3f}'", |
| 91 | + "for x in data: f'{x:.3f}'") |
| 92 | + add("f'{x:.6g}'", |
| 93 | + "for x in data: f'{x:.6g}'") |
| 94 | + add("f'{x!r}'", |
| 95 | + "for x in data: f'{x!r}'") |
| 96 | + add("f'{x}'", |
| 97 | + "for x in data: f'{x}'") |
| 98 | + |
| 99 | + # float.__round__ ndigits >= 0 – mode 3 via Ryu |
| 100 | + add("round(x, 2)", |
| 101 | + "for x in data: round(x, 2)") |
| 102 | + add("round(x, 6)", |
| 103 | + "for x in data: round(x, 6)") |
| 104 | + |
| 105 | + # float.__round__ ndigits < 0 – still uses Gay's dtoa |
| 106 | + add("round(x, -2) [Gay fallback]", |
| 107 | + "for x in data: round(x, -2)", |
| 108 | + values=LARGE + SMALL_INTS) |
| 109 | + |
| 110 | + # specials (inf/nan) – mode 0 |
| 111 | + add("repr(inf/nan)", |
| 112 | + "for x in data: repr(x)", |
| 113 | + values=SPECIALS * 10) |
| 114 | + |
| 115 | + return cases |
| 116 | + |
| 117 | + |
| 118 | +# --------------------------------------------------------------------------- |
| 119 | +# Run benchmark |
| 120 | +# --------------------------------------------------------------------------- |
| 121 | + |
| 122 | +def run_benchmarks(number=500, repeat=7): |
| 123 | + cases = _build_cases() |
| 124 | + results = {} |
| 125 | + |
| 126 | + print(f"Python {sys.version}") |
| 127 | + print(f"{'Case':<35} {'ns/op':>8} {'min ms':>8}") |
| 128 | + print("-" * 60) |
| 129 | + |
| 130 | + for name, stmt, setup in cases: |
| 131 | + times = timeit.repeat(stmt, setup=setup, number=number, repeat=repeat) |
| 132 | + # timeit returns total time for `number` iterations |
| 133 | + # We want per-operation time in ns |
| 134 | + best_total = min(times) # seconds for `number` iters |
| 135 | + # Each iteration processes 1000 items (len of data list) |
| 136 | + n_items = 1000 |
| 137 | + ns_per_op = best_total / number / n_items * 1e9 |
| 138 | + ms_total = best_total * 1000 |
| 139 | + print(f" {name:<33} {ns_per_op:8.1f} {ms_total:8.1f}") |
| 140 | + results[name] = {"ns_per_op": ns_per_op, "min_ms": ms_total} |
| 141 | + |
| 142 | + return results |
| 143 | + |
| 144 | + |
| 145 | +# --------------------------------------------------------------------------- |
| 146 | +# main |
| 147 | +# --------------------------------------------------------------------------- |
| 148 | + |
| 149 | +if __name__ == "__main__": |
| 150 | + emit_json = "--json" in sys.argv |
| 151 | + results = run_benchmarks() |
| 152 | + if emit_json: |
| 153 | + label = sys.argv[sys.argv.index("--label") + 1] if "--label" in sys.argv else "unknown" |
| 154 | + print("\n" + json.dumps({"label": label, "results": results})) |
0 commit comments