benchx 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- benchx/__init__.py +9 -0
- benchx/adapters/__init__.py +10 -0
- benchx/adapters/asv.py +491 -0
- benchx/adapters/asv_runtime.py +326 -0
- benchx/adapters/base.py +143 -0
- benchx/adapters/benchx_params.py +77 -0
- benchx/adapters/gbench.py +217 -0
- benchx/adapters/pyperf.py +468 -0
- benchx/bench.py +113 -0
- benchx/cli.py +625 -0
- benchx/collectors.py +113 -0
- benchx/compare.py +398 -0
- benchx/config.py +193 -0
- benchx/core/__init__.py +70 -0
- benchx/core/catalog.py +97 -0
- benchx/core/errors.py +230 -0
- benchx/core/hashing.py +25 -0
- benchx/core/loader.py +99 -0
- benchx/core/rules.py +156 -0
- benchx/core/validation.py +59 -0
- benchx/errors.py +5 -0
- benchx/harnesses.py +158 -0
- benchx/identity.py +70 -0
- benchx/orders.py +68 -0
- benchx/parquet.py +111 -0
- benchx/projection.py +261 -0
- benchx/runner.py +328 -0
- benchx/schemas/comparison-document/0.1.0/examples/history.json +111 -0
- benchx/schemas/comparison-document/0.1.0/examples/run.json +117 -0
- benchx/schemas/comparison-document/0.1.0/schema.json +620 -0
- benchx/schemas/config/0.1.0/examples/google-benchmark-recommended.json +14 -0
- benchx/schemas/config/0.1.0/examples/pyperf-recommended.json +19 -0
- benchx/schemas/config/0.1.0/schema.json +103 -0
- benchx/schemas/env-identity/0.1.0/examples/arrow-laptop.json +12 -0
- benchx/schemas/env-identity/0.1.0/schema.json +74 -0
- benchx/schemas/environment-policy/0.1.0/examples/laptop-default.json +23 -0
- benchx/schemas/environment-policy/0.1.0/examples/tuned-node.json +35 -0
- benchx/schemas/environment-policy/0.1.0/schema.json +53 -0
- benchx/schemas/identity-policy/0.1.0/examples/arrow.json +28 -0
- benchx/schemas/identity-policy/0.1.0/examples/default.json +20 -0
- benchx/schemas/identity-policy/0.1.0/schema.json +55 -0
- benchx/schemas/measurement-result/0.1.0/examples/adhoc.json +104 -0
- benchx/schemas/measurement-result/0.1.0/examples/arrow-temperature.json +110 -0
- benchx/schemas/measurement-result/0.1.0/examples/arrow.json +157 -0
- benchx/schemas/measurement-result/0.1.0/examples/cupy-matmul-cpu-time.json +173 -0
- benchx/schemas/measurement-result/0.1.0/examples/cupy-matmul-gpu-time.json +173 -0
- benchx/schemas/measurement-result/0.1.0/examples/narwhals-overhead-ratio.json +107 -0
- benchx/schemas/measurement-result/0.1.0/schema.json +724 -0
- benchx/schemas/target-description/0.1.0/examples/arrow-hardened.json +15 -0
- benchx/schemas/target-description/0.1.0/examples/empty-text.json +11 -0
- benchx/schemas/target-description/0.1.0/examples/minimal.json +8 -0
- benchx/schemas/target-description/0.1.0/schema.json +84 -0
- benchx/schemas/target-provider-request/0.1.0/examples/describe.json +5 -0
- benchx/schemas/target-provider-request/0.1.0/examples/prepare.json +6 -0
- benchx/schemas/target-provider-request/0.1.0/schema.json +23 -0
- benchx/schemas/work-order/0.1.0/examples/adhoc-minimal.json +21 -0
- benchx/schemas/work-order/0.1.0/examples/arrow-laptop.json +40 -0
- benchx/schemas/work-order/0.1.0/examples/draft.json +18 -0
- benchx/schemas/work-order/0.1.0/schema.json +406 -0
- benchx/session.py +293 -0
- benchx/snapshot.py +297 -0
- benchx/store.py +323 -0
- benchx/target.py +117 -0
- benchx/tests/conftest.py +182 -0
- benchx/tests/fake_gbench.py +73 -0
- benchx/tests/fixtures/pyperf-calibrated.json +155 -0
- benchx/tests/fixtures/pyperf-native.json +68 -0
- benchx/tests/test_asv.py +421 -0
- benchx/tests/test_bench.py +227 -0
- benchx/tests/test_bench_harnesses.py +275 -0
- benchx/tests/test_benchmark_source.py +157 -0
- benchx/tests/test_build_import_path.py +122 -0
- benchx/tests/test_collectors.py +213 -0
- benchx/tests/test_comparator.py +359 -0
- benchx/tests/test_compare_harnesses.py +167 -0
- benchx/tests/test_config.py +181 -0
- benchx/tests/test_config_schema.py +116 -0
- benchx/tests/test_discovery_timeout.py +148 -0
- benchx/tests/test_e2e_numpy_revisions.py +276 -0
- benchx/tests/test_harnesses.py +66 -0
- benchx/tests/test_loader.py +103 -0
- benchx/tests/test_orders.py +58 -0
- benchx/tests/test_params.py +88 -0
- benchx/tests/test_pipeline.py +77 -0
- benchx/tests/test_projection.py +145 -0
- benchx/tests/test_prototype.py +669 -0
- benchx/tests/test_pyperf.py +502 -0
- benchx/tests/test_rules.py +160 -0
- benchx/tests/test_session.py +152 -0
- benchx/tests/test_sides.py +159 -0
- benchx/tests/test_target.py +216 -0
- benchx/tests/test_uc04.py +132 -0
- benchx/tests/test_validate.py +83 -0
- benchx/tests/test_validation.py +260 -0
- benchx-0.1.0.dist-info/METADATA +261 -0
- benchx-0.1.0.dist-info/RECORD +99 -0
- benchx-0.1.0.dist-info/WHEEL +4 -0
- benchx-0.1.0.dist-info/entry_points.txt +2 -0
- benchx-0.1.0.dist-info/licenses/LICENSE +201 -0
benchx/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""The benchx implementation: the slice of docs/design/prototype-design.md.
|
|
2
|
+
|
|
3
|
+
One module per component behind the `bx` command line: core (reading and
|
|
4
|
+
checking documents), snapshot (what is recorded), adapters.gbench, runner,
|
|
5
|
+
identity, parquet, store, compare, session (the workbench's loop over runner
|
|
6
|
+
and comparator).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Harness adapters (harness-adapter.md). The contract is in `base`."""
|
|
2
|
+
|
|
3
|
+
from . import asv, gbench, pyperf
|
|
4
|
+
|
|
5
|
+
ADAPTERS = {asv.NAME: asv, gbench.NAME: gbench, pyperf.NAME: pyperf}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get(name: str):
|
|
9
|
+
"""The adapter module registered under `name`, or None."""
|
|
10
|
+
return ADAPTERS.get(name)
|
benchx/adapters/asv.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
"""ASV adapter (harness-adapter.md §6.7): asv's benchmark language, timed by pyperf.
|
|
2
|
+
|
|
3
|
+
ASV is treated as a way of writing benchmarks, not as a harness to drive.
|
|
4
|
+
Nothing of asv's is used, neither asv itself nor asv_runner: `asv_runtime`
|
|
5
|
+
(our own, standard library only) reads the suite as asv defines it, and each
|
|
6
|
+
case is timed by pyperf through `Runner.bench_time_func`. The harness in every
|
|
7
|
+
result is therefore pyperf, and the translating half is the pyperf adapter's.
|
|
8
|
+
|
|
9
|
+
Driving: the suite is an ASV benchmark directory inside the target. The
|
|
10
|
+
benchmarks run in the interpreter first on the child's PATH, which must import
|
|
11
|
+
pyperf and the project being measured. A case is one benchmark and, for a
|
|
12
|
+
parameterized one, one parameter combination, named as asv names it
|
|
13
|
+
(`module.Class.time_x-3`). Each case is one pyperf run from a scratch
|
|
14
|
+
directory outside the tree (so an unbuilt source checkout cannot shadow the
|
|
15
|
+
installed project): the pyperf manager runs `setup_cache` once when there is
|
|
16
|
+
one, and each worker runs the setups, then pyperf's warmups and values. Only
|
|
17
|
+
`time_*` benchmarks are cases; `peakmem_*`, `mem_*`, `track_*` and `timeraw_*`
|
|
18
|
+
are listed as not run, since only wall time is mapped.
|
|
19
|
+
|
|
20
|
+
Precision: the work order's levels win; what it leaves out, each benchmark's
|
|
21
|
+
own asv attributes decide, as far as pyperf can express them. `rounds` is not
|
|
22
|
+
read (the order always gives processes); `repeat` gives values (a `(min, max,
|
|
23
|
+
seconds)` repeat gives its minimum: pyperf takes a fixed number); `number`
|
|
24
|
+
gives fixed loops; `sample_time` gives pyperf's `--min-time`; `warmup_time = 0`
|
|
25
|
+
means no warmup, any other a single warmup value; `timeout` is pyperf's
|
|
26
|
+
per-worker `--timeout`, rounded up to whole seconds (asv's default 60 s). Each
|
|
27
|
+
result reports its own case's protocol (`case_protocol`).
|
|
28
|
+
|
|
29
|
+
Setup scope: a benchmark with setup hooks (its own `setup`, or a module-level
|
|
30
|
+
one) declares how often they run with `setup_scope`, looked up like the other
|
|
31
|
+
attributes (function, class, module). "call", the default, is asv_runner's
|
|
32
|
+
since 0.3.0 (asv#966, asv_runner#53): setup runs before every timed call, so
|
|
33
|
+
every call sees freshly set-up state; with no `number` that is one call per
|
|
34
|
+
loop, and with one, setup runs again between calls outside the timed region.
|
|
35
|
+
"sample", as proposed in asv#1613, runs setup once per value and lets the
|
|
36
|
+
calls of a value share its state, so pyperf calibrates loops as usual. It is
|
|
37
|
+
for benchmarks whose calls leave the set-up state as they found it; for a
|
|
38
|
+
fast one under "call", the timing is mostly timer overhead and cold caches,
|
|
39
|
+
and the result carries the `setup-per-call-unbatched` warning.
|
|
40
|
+
|
|
41
|
+
Translating: pyperf's JSON as the pyperf adapter reads it; parameter values
|
|
42
|
+
are kept as asv's repr() strings; asv's `version` (the same hash asv computes)
|
|
43
|
+
is part of the protocol, so editing a benchmark starts a new series.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
import json
|
|
47
|
+
import math
|
|
48
|
+
import os
|
|
49
|
+
import shutil
|
|
50
|
+
import signal
|
|
51
|
+
import statistics
|
|
52
|
+
import subprocess
|
|
53
|
+
import sys
|
|
54
|
+
import tempfile
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
|
|
57
|
+
from .. import snapshot
|
|
58
|
+
from . import benchx_params, pyperf
|
|
59
|
+
from .base import Unsupported, name_only_note, no_cases, parametrized_workload, run_bounded
|
|
60
|
+
|
|
61
|
+
NAME = "asv"
|
|
62
|
+
CONTEXT_KEY = "asv"
|
|
63
|
+
WORKLOAD_PARAMETERS = False
|
|
64
|
+
SUITE_IS_SOURCE = True # the suite is Python source, as pyperf's
|
|
65
|
+
PRODUCER = {"name": "benchx/asv-adapter", "version": "0.2.0", "mapping_version": "asv-on-pyperf/v2"}
|
|
66
|
+
QUANTITIES = pyperf.QUANTITIES
|
|
67
|
+
ENV_ALLOWLIST = pyperf.ENV_ALLOWLIST
|
|
68
|
+
|
|
69
|
+
RUNTIME = Path(__file__).with_name("asv_runtime.py")
|
|
70
|
+
PARAMS = Path(__file__).with_name("benchx_params.py") # the runtime loads it from its own directory
|
|
71
|
+
CONF_NAMES = ("asv.conf.json", "asv.conf.jsonc")
|
|
72
|
+
# asv's own defaults, where an order and a benchmark both leave a setting out.
|
|
73
|
+
DEFAULT_ROUNDS = 2
|
|
74
|
+
DEFAULT_VALUES = 5 # asv's adaptive repeat takes at most 5 samples per round when rounds > 1
|
|
75
|
+
DEFAULT_SAMPLE_TIME = 0.01
|
|
76
|
+
DEFAULT_TIMEOUT = 60.0
|
|
77
|
+
SETUP_SCOPES = ("call", "sample")
|
|
78
|
+
UNBATCHED = "setup-per-call-unbatched"
|
|
79
|
+
# pyperf exits with this when a worker overruns --timeout.
|
|
80
|
+
PYPERF_TIMEOUT_EXIT = 124
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def default_precision() -> dict:
|
|
84
|
+
"""Only the process level: values, calibration and warmup are left to each benchmark."""
|
|
85
|
+
return {"repetitions": {"mode": "fixed", "levels": [{"unit": "process", "n": DEFAULT_ROUNDS}]}}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def protocol(precision: dict) -> tuple[dict, dict]:
|
|
89
|
+
"""The order-level protocol, and what of it each case must apply.
|
|
90
|
+
|
|
91
|
+
The order is pyperf's vocabulary: `process` and `value` levels, fixed
|
|
92
|
+
(`--loops`) or adaptive (`--min-time`) calibration, count warmup. What it
|
|
93
|
+
leaves out is None in the invocation, decided per benchmark (`_plan`).
|
|
94
|
+
"""
|
|
95
|
+
problems, given = [], {}
|
|
96
|
+
repetitions = precision["repetitions"]
|
|
97
|
+
if isinstance(repetitions, int):
|
|
98
|
+
problems.append("pyperf repeats at two levels; give repetitions as "
|
|
99
|
+
"{mode: fixed, levels: [{unit: process, n}, {unit: value, n}]}")
|
|
100
|
+
else:
|
|
101
|
+
for level in repetitions["levels"]:
|
|
102
|
+
if level["unit"] not in ("process", "value") or level["unit"] in given:
|
|
103
|
+
problems.append("pyperf repetition levels are 'process' and 'value', once each")
|
|
104
|
+
break
|
|
105
|
+
given[level["unit"]] = level["n"]
|
|
106
|
+
invocation = {"processes": given.get("process", DEFAULT_ROUNDS), "values": given.get("value"),
|
|
107
|
+
"loops": None, "min_time": None, "warmups": None}
|
|
108
|
+
calibration = precision.get("calibration")
|
|
109
|
+
if calibration:
|
|
110
|
+
if calibration["mode"] == "fixed":
|
|
111
|
+
invocation["loops"] = calibration["n_iterations"]
|
|
112
|
+
else:
|
|
113
|
+
invocation["min_time"] = calibration["minimum_sample_seconds"]
|
|
114
|
+
warmup = precision.get("warmup")
|
|
115
|
+
if warmup:
|
|
116
|
+
if warmup["mode"] == "time":
|
|
117
|
+
problems.append("pyperf warmup is count-based only, not time-based")
|
|
118
|
+
else:
|
|
119
|
+
invocation["warmups"] = warmup.get("n_warmup", 0)
|
|
120
|
+
if problems:
|
|
121
|
+
raise Unsupported(*problems)
|
|
122
|
+
levels = [{"unit": "process", "n": invocation["processes"]}]
|
|
123
|
+
if invocation["values"] is not None:
|
|
124
|
+
levels.append({"unit": "value", "n": invocation["values"]})
|
|
125
|
+
applied = {"repetitions": {"mode": "fixed", "levels": levels}, "timer": "perf_counter", "gc": "disabled",
|
|
126
|
+
"environment": "inherit-all"}
|
|
127
|
+
if calibration:
|
|
128
|
+
applied["calibration"] = calibration
|
|
129
|
+
if warmup:
|
|
130
|
+
applied["warmup"] = warmup
|
|
131
|
+
return applied, invocation
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _which_python(env: dict) -> str | None:
|
|
135
|
+
path = env.get("PATH", "")
|
|
136
|
+
return shutil.which("python", path=path) or shutil.which("python3", path=path)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _read_conf(path: Path) -> dict:
|
|
140
|
+
"""asv.conf.json allows // comments; drop whole-line ones, as asv does."""
|
|
141
|
+
lines = [l for l in path.read_text(encoding="utf-8").splitlines() if not l.lstrip().startswith("//")]
|
|
142
|
+
try:
|
|
143
|
+
return json.loads("\n".join(lines))
|
|
144
|
+
except ValueError:
|
|
145
|
+
return {}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _project(benchmark_dir: Path, root: Path) -> str | None:
|
|
149
|
+
"""The `project` of the nearest asv.conf.json at or above the benchmark directory, within the tree."""
|
|
150
|
+
for directory in [benchmark_dir, *benchmark_dir.parents]:
|
|
151
|
+
for name in CONF_NAMES:
|
|
152
|
+
if (directory / name).is_file():
|
|
153
|
+
return _read_conf(directory / name).get("project")
|
|
154
|
+
if directory == root:
|
|
155
|
+
break
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def locate(target_path, suite, env, timeout=None) -> dict:
|
|
160
|
+
"""The benchmark directory, the interpreter that will run it, and the project it measures."""
|
|
161
|
+
root = Path(target_path).resolve()
|
|
162
|
+
benchmark_dir = (root / suite).resolve()
|
|
163
|
+
if not benchmark_dir.is_dir():
|
|
164
|
+
raise Unsupported(f"suite is not an asv benchmark directory: {benchmark_dir}")
|
|
165
|
+
python = _which_python(env)
|
|
166
|
+
if python is None:
|
|
167
|
+
raise Unsupported("no `python` on the PATH the benchmark would run with")
|
|
168
|
+
probe = run_bounded([python, "-c", "import pyperf"], timeout=timeout, what=f"importing pyperf with {python}",
|
|
169
|
+
env=env)
|
|
170
|
+
if probe.returncode != 0:
|
|
171
|
+
raise Unsupported(f"pyperf is not importable by {python}: {probe.stderr.strip().splitlines()[-1:]}")
|
|
172
|
+
return {"python": python, "benchmark_dir": benchmark_dir, "root": root,
|
|
173
|
+
"project": _project(benchmark_dir, root), "benchmarks": {}}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def list_cases(runnable, case_filter, env, timeout=None) -> list[str]:
|
|
177
|
+
"""The `time_*` benchmarks the filter (a regex, as asv's --bench) selects,
|
|
178
|
+
one case per parameter combination. As in asv, a parametrized benchmark is
|
|
179
|
+
searched once per combination, as `name(p0, p1)`, and only the matching
|
|
180
|
+
combinations run. Modules that fail to import and benchmarks of other types
|
|
181
|
+
are reported on stderr, never run."""
|
|
182
|
+
with tempfile.TemporaryDirectory() as scratch:
|
|
183
|
+
# A copy, so the script's directory on sys.path holds nothing else (adapters/ has a pyperf.py).
|
|
184
|
+
runtime = shutil.copy(RUNTIME, scratch)
|
|
185
|
+
shutil.copy(PARAMS, scratch)
|
|
186
|
+
out = run_bounded([runnable["python"], runtime, "list", str(runnable["benchmark_dir"])],
|
|
187
|
+
timeout=timeout, what=f"listing the asv benchmarks in {runnable['benchmark_dir']}",
|
|
188
|
+
env=env, cwd=scratch)
|
|
189
|
+
if out.returncode != 0:
|
|
190
|
+
raise Unsupported(f"cannot discover asv benchmarks in {runnable['benchmark_dir']}: "
|
|
191
|
+
f"{(out.stderr.strip().splitlines() or ['no output'])[-1]}")
|
|
192
|
+
listing = json.loads(out.stdout.strip().splitlines()[-1])
|
|
193
|
+
for failure in listing["failed"]:
|
|
194
|
+
print(f"asv: skipped module {failure['module']}: {failure['error']}", file=sys.stderr)
|
|
195
|
+
cases, other, unmatched = [], {}, []
|
|
196
|
+
runnable["cases"] = {} # case id -> (benchmark name, combination index or None)
|
|
197
|
+
for info in listing["benchmarks"]:
|
|
198
|
+
selected = [(case, (info["name"], index))
|
|
199
|
+
for case, index in benchx_params.expand(info["name"], info["params"], case_filter)]
|
|
200
|
+
if not selected:
|
|
201
|
+
if benchx_params.matches_name_only(info["name"], info["params"], case_filter):
|
|
202
|
+
unmatched.append(info["name"])
|
|
203
|
+
continue
|
|
204
|
+
if info["type"] != "time":
|
|
205
|
+
other[info["type"]] = other.get(info["type"], 0) + 1
|
|
206
|
+
continue
|
|
207
|
+
scope = info["declared"].get("setup_scope", "call")
|
|
208
|
+
if scope not in SETUP_SCOPES:
|
|
209
|
+
print(f"asv: skipped {info['name']}: setup_scope must be one of {', '.join(map(repr, SETUP_SCOPES))}, "
|
|
210
|
+
f"not {scope!r}", file=sys.stderr)
|
|
211
|
+
continue
|
|
212
|
+
runnable["benchmarks"][info["name"]] = info
|
|
213
|
+
for case, target in selected:
|
|
214
|
+
if runnable["cases"].setdefault(case, target) != target:
|
|
215
|
+
raise Unsupported(f"asv benchmarks {_describe(runnable['cases'][case])} and {_describe(target)} "
|
|
216
|
+
f"share the case id {case!r}; give one of them another benchmark_name")
|
|
217
|
+
cases.append(case)
|
|
218
|
+
not_run = ", ".join(f"{n} {t}" for t, n in sorted(other.items()))
|
|
219
|
+
if not cases:
|
|
220
|
+
notes = []
|
|
221
|
+
if unmatched:
|
|
222
|
+
notes.append(name_only_note(unmatched))
|
|
223
|
+
if other:
|
|
224
|
+
notes.append(f"only benchmarks that are not run were selected (only time benchmarks map to wall-time): "
|
|
225
|
+
f"{not_run}")
|
|
226
|
+
if listing["failed"]:
|
|
227
|
+
notes.append(f"{len(listing['failed'])} module(s) failed to import")
|
|
228
|
+
raise no_cases(runnable["benchmark_dir"], case_filter,
|
|
229
|
+
{i["name"] for i in listing["benchmarks"] if i["type"] == "time"}, notes)
|
|
230
|
+
if other:
|
|
231
|
+
print(f"asv: not run (only time benchmarks map to wall-time): {not_run}", file=sys.stderr)
|
|
232
|
+
return cases
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _describe(target: tuple[str, int | None]) -> str:
|
|
236
|
+
name, index = target
|
|
237
|
+
return repr(name) if index is None else f"{name!r} (combination {index})"
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
workload = parametrized_workload # the benchmark name, and its parameters as asv's repr() strings
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _plan(info: dict, invocation: dict) -> dict:
|
|
244
|
+
"""The pyperf settings one case runs with: the order's, then the benchmark's, then asv's defaults."""
|
|
245
|
+
declared = info["declared"]
|
|
246
|
+
values, source = invocation["values"], "order"
|
|
247
|
+
if values is None:
|
|
248
|
+
repeat = declared.get("repeat")
|
|
249
|
+
if isinstance(repeat, int) and repeat > 0:
|
|
250
|
+
values, source = repeat, "repeat"
|
|
251
|
+
elif isinstance(repeat, list) and len(repeat) == 3:
|
|
252
|
+
values, source = int(repeat[0]), "repeat-min"
|
|
253
|
+
else:
|
|
254
|
+
values, source = DEFAULT_VALUES, "default"
|
|
255
|
+
loops, loops_from = invocation["loops"], "order"
|
|
256
|
+
if loops is None and int(declared.get("number", 0)) > 0:
|
|
257
|
+
loops, loops_from = int(declared["number"]), "number"
|
|
258
|
+
scope = declared.get("setup_scope", "call") if info["has_setup"] else None
|
|
259
|
+
if loops is None and scope == "call":
|
|
260
|
+
loops, loops_from = 1, "setup_scope" # every timed call sees fresh state
|
|
261
|
+
elif loops is None:
|
|
262
|
+
loops_from = None
|
|
263
|
+
min_time = invocation["min_time"] if invocation["min_time"] is not None else declared.get(
|
|
264
|
+
"sample_time", DEFAULT_SAMPLE_TIME)
|
|
265
|
+
warmups = invocation["warmups"]
|
|
266
|
+
if warmups is None:
|
|
267
|
+
warmups = 0 if declared.get("warmup_time") == 0 else 1
|
|
268
|
+
return {"processes": invocation["processes"], "values": values, "values_from": source, "loops": loops,
|
|
269
|
+
"min_time": min_time, "warmups": warmups, "timeout": float(declared.get("timeout", DEFAULT_TIMEOUT)),
|
|
270
|
+
"loops_from": loops_from, "setup_scope": scope}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _flags(plan: dict) -> list[str]:
|
|
274
|
+
flags = ["--processes", str(plan["processes"]), "--values", str(plan["values"]),
|
|
275
|
+
"--warmups", str(plan["warmups"]), "--timeout", str(math.ceil(plan["timeout"])), "--copy-env"]
|
|
276
|
+
if plan["loops"] is not None:
|
|
277
|
+
return flags + ["--loops", str(plan["loops"])]
|
|
278
|
+
return flags + ["--min-time", str(plan["min_time"])]
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
DRIVER = '''\
|
|
282
|
+
# Generated by benchx. Runs one asv benchmark case under pyperf.
|
|
283
|
+
import hashlib, json, os, sys
|
|
284
|
+
from pathlib import Path
|
|
285
|
+
|
|
286
|
+
# Before anything of the user's is imported: what this process was given.
|
|
287
|
+
_ENV = dict(os.environ)
|
|
288
|
+
_DIGEST = hashlib.sha256(
|
|
289
|
+
json.dumps(_ENV, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
|
|
290
|
+
|
|
291
|
+
import importlib.metadata, importlib.util, pickle
|
|
292
|
+
import pyperf
|
|
293
|
+
|
|
294
|
+
spec = importlib.util.spec_from_file_location("benchx_asv_runtime", {runtime!r})
|
|
295
|
+
rt = importlib.util.module_from_spec(spec)
|
|
296
|
+
sys.modules["benchx_asv_runtime"] = rt
|
|
297
|
+
spec.loader.exec_module(rt)
|
|
298
|
+
|
|
299
|
+
runner = pyperf.Runner()
|
|
300
|
+
runner.parse_args()
|
|
301
|
+
runner.metadata[{digest_key!r}] = _DIGEST
|
|
302
|
+
|
|
303
|
+
if not runner.args.worker:
|
|
304
|
+
if {has_cache!r}:
|
|
305
|
+
# asv's setup_cache step: once per case, before any worker, in the shared scratch directory.
|
|
306
|
+
bench = rt.load({benchmark_dir!r}, {module!r}, {attr!r}, {index!r})
|
|
307
|
+
Path("cache.pickle").write_bytes(pickle.dumps(bench.prepare_cache()))
|
|
308
|
+
runner.bench_time_func({case!r}, lambda loops: 0.0) # the manager only spawns workers
|
|
309
|
+
sys.exit(0)
|
|
310
|
+
|
|
311
|
+
# Only the allowlisted names: the digest above covers the whole environment,
|
|
312
|
+
# the file is shared, and CI environments carry secrets.
|
|
313
|
+
Path({worker_env!r}).write_text(json.dumps({{k: _ENV[k] for k in {env_names!r} if k in _ENV}}, sort_keys=True, indent=1))
|
|
314
|
+
bench = rt.load({benchmark_dir!r}, {module!r}, {attr!r}, {index!r})
|
|
315
|
+
if {has_cache!r}:
|
|
316
|
+
bench.set_cache(pickle.loads(Path("cache.pickle").read_bytes()))
|
|
317
|
+
try:
|
|
318
|
+
bench.setup()
|
|
319
|
+
except rt.Skipped as e:
|
|
320
|
+
Path({skipped!r}).write_text(json.dumps({{"reason": str(e)}}))
|
|
321
|
+
sys.exit(0)
|
|
322
|
+
|
|
323
|
+
project = {project!r}
|
|
324
|
+
if project:
|
|
325
|
+
installed = {{"name": project}}
|
|
326
|
+
try:
|
|
327
|
+
installed["version"] = importlib.metadata.version(project)
|
|
328
|
+
except importlib.metadata.PackageNotFoundError:
|
|
329
|
+
pass
|
|
330
|
+
module = sys.modules.get(project)
|
|
331
|
+
if module is not None:
|
|
332
|
+
installed["path"] = getattr(module, "__file__", None)
|
|
333
|
+
for attr in ("__version__", "__git_version__"):
|
|
334
|
+
if isinstance(getattr(module, attr, None), str):
|
|
335
|
+
installed[attr.strip("_")] = getattr(module, attr)
|
|
336
|
+
Path({facts!r}).write_text(json.dumps({{"project": installed}}))
|
|
337
|
+
try:
|
|
338
|
+
runner.bench_time_func({case!r}, bench.time_func())
|
|
339
|
+
finally:
|
|
340
|
+
bench.teardown()
|
|
341
|
+
'''
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _read_json(path: Path):
|
|
345
|
+
try:
|
|
346
|
+
return json.loads(path.read_text())
|
|
347
|
+
except (OSError, ValueError):
|
|
348
|
+
return None
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def run_case(runnable, case, invocation, env, timeout, native_path, env_names=None) -> dict:
|
|
352
|
+
"""One pyperf run for the case; never raises for harness failures, which become results."""
|
|
353
|
+
if env_names is None:
|
|
354
|
+
env_names = snapshot.env_allowlist(env, ENV_ALLOWLIST)
|
|
355
|
+
name, index = runnable["cases"][case]
|
|
356
|
+
info = runnable["benchmarks"][name]
|
|
357
|
+
plan = _plan(info, invocation)
|
|
358
|
+
stem = native_path.name.removesuffix(".native.json")
|
|
359
|
+
driver = native_path.with_name(f"{stem}.driver.py")
|
|
360
|
+
worker_env = native_path.with_name(f"{stem}.worker-env.json")
|
|
361
|
+
sidecar = native_path.with_name(f"{stem}.asv.json")
|
|
362
|
+
runtime = native_path.with_name("asv_runtime.py")
|
|
363
|
+
params = native_path.with_name(PARAMS.name)
|
|
364
|
+
shutil.copyfile(RUNTIME, runtime)
|
|
365
|
+
shutil.copyfile(PARAMS, params)
|
|
366
|
+
for stale in (native_path, worker_env, sidecar):
|
|
367
|
+
stale.unlink(missing_ok=True)
|
|
368
|
+
with tempfile.TemporaryDirectory() as scratch:
|
|
369
|
+
skipped, facts = Path(scratch, "skipped.json"), Path(scratch, "facts.json")
|
|
370
|
+
driver.write_text(DRIVER.format(
|
|
371
|
+
runtime=str(runtime.resolve()), digest_key=pyperf.ENV_DIGEST_KEY, worker_env=str(worker_env.resolve()),
|
|
372
|
+
env_names=list(env_names), benchmark_dir=str(runnable["benchmark_dir"]), module=info["module"],
|
|
373
|
+
attr=info["attr"], index=index, case=case, has_cache=bool(info["setup_cache_key"]),
|
|
374
|
+
skipped=str(skipped), facts=str(facts), project=runnable["project"] or ""))
|
|
375
|
+
args = [runnable["python"], str(driver.resolve()), *_flags(plan), "-o", str(native_path.resolve())]
|
|
376
|
+
# Its own process group, so a timeout takes the workers down with the manager.
|
|
377
|
+
proc = subprocess.Popen(args, env=env, cwd=scratch, text=True, start_new_session=True,
|
|
378
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
379
|
+
try:
|
|
380
|
+
stdout, stderr = proc.communicate(timeout=timeout)
|
|
381
|
+
status = proc.returncode
|
|
382
|
+
except subprocess.TimeoutExpired:
|
|
383
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
384
|
+
stdout, stderr = proc.communicate()
|
|
385
|
+
status = None
|
|
386
|
+
skip = _read_json(skipped)
|
|
387
|
+
observed = _read_json(facts) or {}
|
|
388
|
+
native = _read_json(native_path)
|
|
389
|
+
if native is not None:
|
|
390
|
+
native_path.write_text(json.dumps(native, indent=1) + "\n")
|
|
391
|
+
asv = {"benchmark": info, "case": case, "plan": plan, "skipped": skip, **observed}
|
|
392
|
+
sidecar.write_text(json.dumps(asv, indent=1) + "\n")
|
|
393
|
+
artifacts = [("driver", "text/x-python", driver), ("asv-runtime", "text/x-python", runtime),
|
|
394
|
+
("params-helper", "text/x-python", params), ("asv-case", "application/json", sidecar)]
|
|
395
|
+
if worker_env.exists():
|
|
396
|
+
artifacts.append(("worker-environment", "application/json", worker_env))
|
|
397
|
+
# A worker over the benchmark's own timeout: pyperf's manager gives up with 124.
|
|
398
|
+
worker_timeout = status == PYPERF_TIMEOUT_EXIT and "timed out after" in (stdout or "").lower()
|
|
399
|
+
return {"exit_status": status, "timed_out": status is None or worker_timeout,
|
|
400
|
+
"stdout": stdout or "", "stderr": stderr or "",
|
|
401
|
+
"native": {**(native or {"benchmarks": []}), "benchx_asv": asv}, "artifacts": artifacts,
|
|
402
|
+
"worker_env": _read_json(worker_env), "passed_env_digest": pyperf.env_digest(env)}
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _case_applied(applied: dict, plan: dict, version: str | None = None) -> dict:
|
|
406
|
+
"""The protocol one case ran under, in benchx terms."""
|
|
407
|
+
if plan["loops"] is not None:
|
|
408
|
+
calibration = {"mode": "fixed", "n_iterations": plan["loops"]}
|
|
409
|
+
else:
|
|
410
|
+
calibration = {"mode": "adaptive", "minimum_sample_seconds": plan["min_time"]}
|
|
411
|
+
warmup = {"mode": "count", "n_warmup": plan["warmups"]} if plan["warmups"] else {"mode": "none"}
|
|
412
|
+
asv = {k: plan[k] for k in ("values_from", "timeout")}
|
|
413
|
+
if plan["setup_scope"]:
|
|
414
|
+
asv["setup_scope"] = plan["setup_scope"]
|
|
415
|
+
if version:
|
|
416
|
+
asv["benchmark_version"] = version
|
|
417
|
+
return {**applied, "repetitions": {"mode": "fixed", "levels": [{"unit": "process", "n": plan["processes"]},
|
|
418
|
+
{"unit": "value", "n": plan["values"]}]},
|
|
419
|
+
"calibration": calibration, "warmup": warmup, "asv": asv}
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def case_protocol(applied: dict, run: dict, case: str) -> dict:
|
|
423
|
+
asv = run["native"]["benchx_asv"]
|
|
424
|
+
return _case_applied(applied, asv["plan"], asv["benchmark"].get("version"))
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def attempted(applied: dict) -> int:
|
|
428
|
+
"""Order-level; each case's own count comes from its plan (`translate`)."""
|
|
429
|
+
n = 1
|
|
430
|
+
for level in applied["repetitions"]["levels"]:
|
|
431
|
+
n *= level["n"]
|
|
432
|
+
return n
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def repetition_levels(applied: dict, run: dict, case: str) -> list[dict]:
|
|
436
|
+
return pyperf.repetition_levels(case_protocol(applied, run, case), run, case)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def translate(case: str, quantities: list[str], run: dict, attempted_: int) -> list[dict]:
|
|
440
|
+
asv = run["native"]["benchx_asv"]
|
|
441
|
+
plan = asv["plan"]
|
|
442
|
+
planned = plan["processes"] * plan["values"]
|
|
443
|
+
if asv.get("skipped") is not None:
|
|
444
|
+
return [{"quantity": QUANTITIES[name][1],
|
|
445
|
+
"measurement": {"status": "skipped", "reason": "harness.skipped"},
|
|
446
|
+
"procedure": {"attempted_repetitions": planned, "completed_repetitions": 0},
|
|
447
|
+
"info": {"message": asv["skipped"]["reason"]}} for name in quantities]
|
|
448
|
+
return pyperf.translate(case, quantities, run, planned)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def harness(info: dict) -> dict:
|
|
452
|
+
return pyperf.harness(info)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def context_facts(native: dict | None) -> tuple[dict, dict]:
|
|
456
|
+
"""pyperf's facts; in provenance, the installed project the workers saw (it
|
|
457
|
+
changes with the revision, so it is never a system fact) and the benchmark's
|
|
458
|
+
declared attributes. The benchmark's `version` is in its protocol (`case_protocol`)."""
|
|
459
|
+
native = native or {}
|
|
460
|
+
system, info = pyperf.context_facts(native)
|
|
461
|
+
asv = native.get("benchx_asv", {})
|
|
462
|
+
if asv.get("project"):
|
|
463
|
+
info["installed"] = asv["project"]
|
|
464
|
+
benchmark = asv.get("benchmark")
|
|
465
|
+
if benchmark:
|
|
466
|
+
if benchmark.get("version"):
|
|
467
|
+
info["benchmark_version"] = benchmark["version"]
|
|
468
|
+
if benchmark.get("declared"):
|
|
469
|
+
info["declared"] = benchmark["declared"]
|
|
470
|
+
if benchmark.get("setup_cache_key"):
|
|
471
|
+
info["setup_cache_key"] = benchmark["setup_cache_key"]
|
|
472
|
+
return system, info
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _unbatched(run: dict, case: str) -> bool:
|
|
476
|
+
"""Setup before every call kept pyperf from batching calls it would have:
|
|
477
|
+
the order left loops to the benchmark, and a call is shorter than a value
|
|
478
|
+
is meant to take."""
|
|
479
|
+
plan = run["native"]["benchx_asv"]["plan"]
|
|
480
|
+
if plan["setup_scope"] != "call" or plan["loops_from"] == "order":
|
|
481
|
+
return False
|
|
482
|
+
benchmark = pyperf._benchmark(run["native"], case)
|
|
483
|
+
values = [v for r, _ in (pyperf._runs(run["native"], benchmark) if benchmark else []) for v in r.get("values", [])]
|
|
484
|
+
return bool(values) and statistics.median(values) < plan["min_time"]
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def observed_environment(run: dict, case: str, env_names) -> tuple[dict, list[str]]:
|
|
488
|
+
facts, warnings = pyperf.observed_environment(run, case, env_names)
|
|
489
|
+
if _unbatched(run, case):
|
|
490
|
+
warnings.append(UNBATCHED)
|
|
491
|
+
return facts, warnings
|