Skip to content

Commit eb03318

Browse files
committed
STYLE: format codebase with ruff
1 parent b564411 commit eb03318

86 files changed

Lines changed: 6755 additions & 2742 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/benchx/adapters/asv.py‎

Lines changed: 206 additions & 74 deletions
Large diffs are not rendered by default.

‎src/benchx/adapters/asv_runtime.py‎

Lines changed: 49 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ def _load_params():
3737
if "benchx_params" in sys.modules:
3838
return sys.modules["benchx_params"]
3939
spec = importlib.util.spec_from_file_location(
40-
"benchx_params", os.path.join(os.path.dirname(os.path.abspath(__file__)), "benchx_params.py"))
40+
"benchx_params", os.path.join(os.path.dirname(os.path.abspath(__file__)), "benchx_params.py")
41+
)
4142
module = importlib.util.module_from_spec(spec)
4243
sys.modules["benchx_params"] = module
4344
spec.loader.exec_module(module)
@@ -55,8 +56,17 @@ def _load_params():
5556
("track", re.compile("^(Track[A-Z_].+)|(track_.+)$")),
5657
)
5758
# Declared attributes that bear on how a case is timed.
58-
DECLARED = ("number", "repeat", "rounds", "processes", "sample_time", "warmup_time", "min_run_count", "timeout",
59-
"setup_scope")
59+
DECLARED = (
60+
"number",
61+
"repeat",
62+
"rounds",
63+
"processes",
64+
"sample_time",
65+
"warmup_time",
66+
"min_run_count",
67+
"timeout",
68+
"setup_scope",
69+
)
6070

6171

6272
class Skipped(Exception):
@@ -151,21 +161,34 @@ def __init__(self, name, kind, func, sources, module, attr):
151161
explicit = _first(sources, "version")
152162
code = _source([func] + self.setups + [self.setup_cache])
153163
self.version = str(explicit) if explicit is not None else hashlib.sha256(code.encode()).hexdigest()
154-
self.raw_params, self.param_names, self.params = params_.normalize(_first(sources, "params", []),
155-
_first(sources, "param_names", []))
164+
self.raw_params, self.param_names, self.params = params_.normalize(
165+
_first(sources, "params", []), _first(sources, "param_names", [])
166+
)
156167
self.skip_params = _first(sources, "skip_params", [])
157168
self.declared = {k: _first(sources, k) for k in DECLARED if _first(sources, k) is not None}
158169
self.timer = _first(sources, "timer", time.perf_counter)
159170
self.current, self.cache, self._has_cache = (), None, False
160171

161172
def describe(self) -> dict:
162173
"""What the adapter needs to plan and record a case, as JSON."""
163-
declared = {k: (list(v) if isinstance(v, tuple) else v) for k, v in self.declared.items()
164-
if isinstance(v, (int, float, str, tuple, list))}
165-
return {"name": self.name, "type": self.type, "module": self.module, "attr": self.attr,
166-
"params": self.params, "param_names": self.param_names, "version": self.version,
167-
"setup_cache_key": self.setup_cache_key, "has_setup": bool(self.setups),
168-
"has_teardown": bool(self.teardowns), "declared": declared}
174+
declared = {
175+
k: (list(v) if isinstance(v, tuple) else v)
176+
for k, v in self.declared.items()
177+
if isinstance(v, (int, float, str, tuple, list))
178+
}
179+
return {
180+
"name": self.name,
181+
"type": self.type,
182+
"module": self.module,
183+
"attr": self.attr,
184+
"params": self.params,
185+
"param_names": self.param_names,
186+
"version": self.version,
187+
"setup_cache_key": self.setup_cache_key,
188+
"has_setup": bool(self.setups),
189+
"has_teardown": bool(self.teardowns),
190+
"declared": declared,
191+
}
169192

170193
def select(self, index):
171194
if index is not None:
@@ -211,6 +234,7 @@ def time_func(self):
211234
func, args, timer = self.func, self._args(), self.timer
212235
fresh = [True] # the first value (or call) uses the setup the driver ran
213236
if not self.setups or self.declared.get("setup_scope", "call") == "sample":
237+
214238
def run(loops):
215239
if self.setups and not fresh[0]:
216240
self.teardown()
@@ -226,6 +250,7 @@ def run(loops):
226250
finally:
227251
if enabled:
228252
gc.enable()
253+
229254
return run
230255

231256
def run_isolated(loops):
@@ -245,6 +270,7 @@ def run_isolated(loops):
245270
if enabled:
246271
gc.enable()
247272
return total
273+
248274
return run_isolated
249275

250276

@@ -260,20 +286,26 @@ def _benchmark(attr_name, module, klass, func, left_out=None):
260286
return None
261287
parts = module.__name__.split(".", 1)[1:]
262288
if klass is None:
263-
return Benchmark(name or ".".join(parts + [func.__name__]), kind, func, [func, module],
264-
module.__name__, [attr_name])
289+
return Benchmark(
290+
name or ".".join(parts + [func.__name__]), kind, func, [func, module], module.__name__, [attr_name]
291+
)
265292
instance = klass()
266293
bound = getattr(instance, attr_name)
267-
return Benchmark(name or ".".join(parts + [klass.__name__, attr_name]), kind, bound,
268-
[bound, instance, module], module.__name__, [klass.__name__, attr_name])
294+
return Benchmark(
295+
name or ".".join(parts + [klass.__name__, attr_name]),
296+
kind,
297+
bound,
298+
[bound, instance, module],
299+
module.__name__,
300+
[klass.__name__, attr_name],
301+
)
269302

270303

271304
def _modules(name, failed):
272305
try:
273306
module = importlib.import_module(name)
274307
except BaseException as e:
275-
failed.append({"module": name, "error": f"{type(e).__name__}: {e}",
276-
"traceback": traceback.format_exc()})
308+
failed.append({"module": name, "error": f"{type(e).__name__}: {e}", "traceback": traceback.format_exc()})
277309
return
278310
yield module
279311
for _, sub, _ in pkgutil.iter_modules(getattr(module, "__path__", None) or [], name + "."):

‎src/benchx/adapters/base.py‎

Lines changed: 43 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,15 @@ def name_only_note(found) -> str:
114114
is searched, with the first benchmark's parameters, in order, and one case as it is searched."""
115115
first = found[0]
116116
names = ", ".join(info["name"] for info in found[:3])
117-
return "\n".join([
118-
f"the filter matches the name of a parametrized benchmark ({names}) but not its arguments.",
119-
"They are searched as name(p0, p1), each as its repr, in the order of param_names:",
120-
f" {first['name']}({', '.join(first['param_names'])})",
121-
"for example:",
122-
f" {search_name(first['name'], first['params'], 0)}"])
117+
return "\n".join(
118+
[
119+
f"the filter matches the name of a parametrized benchmark ({names}) but not its arguments.",
120+
"They are searched as name(p0, p1), each as its repr, in the order of param_names:",
121+
f" {first['name']}({', '.join(first['param_names'])})",
122+
"for example:",
123+
f" {search_name(first['name'], first['params'], 0)}",
124+
]
125+
)
123126

124127

125128
def similar(case_filter, names, limit=5, cutoff=0.75) -> list[str]:
@@ -178,8 +181,9 @@ def last_json(out: subprocess.CompletedProcess, what: str):
178181
return json.loads(lines[-1])
179182
except (IndexError, ValueError):
180183
found = f"its last line of output is {lines[-1][:80]!r}" if lines else "it printed nothing"
181-
raise Unsupported(f"cannot read the benchmark listing of {what}: {found}, not the JSON "
182-
"the listing ends with") from None
184+
raise Unsupported(
185+
f"cannot read the benchmark listing of {what}: {found}, not the JSON the listing ends with"
186+
) from None
183187

184188

185189
# How long a benchmark's manager gets to tidy up after Ctrl-C before its group is killed. pyperf, given Ctrl-C on its
@@ -207,8 +211,10 @@ def kill_group(proc) -> tuple[str, str]:
207211
for pipe in (proc.stdout, proc.stderr): # what arrived is in the exception, as bytes
208212
if pipe is not None:
209213
pipe.close()
210-
return tuple(data.decode(errors="backslashreplace") if isinstance(data, bytes) else data or ""
211-
for data in (holding.stdout, holding.stderr))
214+
return tuple(
215+
data.decode(errors="backslashreplace") if isinstance(data, bytes) else data or ""
216+
for data in (holding.stdout, holding.stderr)
217+
)
212218

213219

214220
def stop_group(proc, grace=STOP_GRACE_S) -> None:
@@ -231,8 +237,13 @@ def note_cases(adapter_logger, cases, case_filter, limit=40) -> list:
231237
"""What `list_cases` found, for the log: how many, under which filter, and the first `limit` names."""
232238
shown = cases[:limit]
233239
more = f", and {len(cases) - len(shown)} more" if len(cases) > len(shown) else ""
234-
adapter_logger.debug("%d case(s)%s: %s%s", len(cases), f" for the filter {case_filter!r}" if case_filter else "",
235-
", ".join(shown), more)
240+
adapter_logger.debug(
241+
"%d case(s)%s: %s%s",
242+
len(cases),
243+
f" for the filter {case_filter!r}" if case_filter else "",
244+
", ".join(shown),
245+
more,
246+
)
236247
return cases
237248

238249

@@ -241,10 +252,13 @@ def note_parameters(adapter_logger, runnable, limit=40) -> None:
241252
strings) and the number of combinations, one case each. At most `limit` benchmarks."""
242253
found = [(name, info) for name, info in runnable.get("benchmarks", {}).items() if info.get("param_names")]
243254
for name, info in found[:limit]:
244-
values = ", ".join(f"{parameter}: {', '.join(shown[:10])}{', …' if len(shown) > 10 else ''}"
245-
for parameter, shown in zip(info["param_names"], info["params"]))
246-
adapter_logger.debug("%s: %d combination(s) of %s", name, math.prod(len(shown) for shown in info["params"]),
247-
values)
255+
values = ", ".join(
256+
f"{parameter}: {', '.join(shown[:10])}{', …' if len(shown) > 10 else ''}"
257+
for parameter, shown in zip(info["param_names"], info["params"])
258+
)
259+
adapter_logger.debug(
260+
"%s: %d combination(s) of %s", name, math.prod(len(shown) for shown in info["params"]), values
261+
)
248262
if len(found) > limit:
249263
adapter_logger.debug("and %d more parametrized benchmark(s)", len(found) - limit)
250264

@@ -264,7 +278,9 @@ def note_case_ended(adapter_logger, status, timeout, native_path, *, parsed, ski
264278
adapter_logger.debug("timed out after %g s: the process group was killed", timeout)
265279
if not native_path.exists():
266280
if not skipped:
267-
adapter_logger.log(logging.WARNING if status == 0 else logging.DEBUG, "native output missing: %s", native_path)
281+
adapter_logger.log(
282+
logging.WARNING if status == 0 else logging.DEBUG, "native output missing: %s", native_path
283+
)
268284
elif not parsed:
269285
adapter_logger.warning("native output does not parse: %s", native_path)
270286

@@ -278,11 +294,17 @@ def run_bounded(args, *, timeout, what, scripts=None, temporary=(), **kwargs) ->
278294
`what` was being done: an order whose discovery cannot finish cannot be planned.
279295
`timeout` None means no limit.
280296
"""
281-
logger.debug("%s: %s (in %s, limit %s)", what, log.command(args, scripts=scripts, temporary=temporary),
282-
kwargs.get("cwd") or Path.cwd(), f"{timeout:g} s" if timeout else "none")
297+
logger.debug(
298+
"%s: %s (in %s, limit %s)",
299+
what,
300+
log.command(args, scripts=scripts, temporary=temporary),
301+
kwargs.get("cwd") or Path.cwd(),
302+
f"{timeout:g} s" if timeout else "none",
303+
)
283304
started = time.monotonic()
284-
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
285-
start_new_session=True, **kwargs)
305+
proc = subprocess.Popen(
306+
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, **kwargs
307+
)
286308
try:
287309
stdout, stderr = proc.communicate(timeout=timeout)
288310
except BaseException as error:

‎src/benchx/adapters/benchx_params.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def normalize(params, param_names):
5757
params = [params]
5858
else:
5959
params = [list(entry) for entry in params]
60-
param_names = [str(n) for n in param_names][:len(params)]
60+
param_names = [str(n) for n in param_names][: len(params)]
6161
param_names += [f"param{k + 1}" for k in range(len(param_names), len(params))]
6262
ids = []
6363
for entry in params:
@@ -99,8 +99,11 @@ def expand(name, ids, case_filter):
9999
"""
100100
if not ids:
101101
return [(name, None)] if not case_filter or re.search(case_filter, name) else []
102-
return [(f"{name}-{i}", i) for i, combo in enumerate(itertools.product(*ids))
103-
if not case_filter or re.search(case_filter, _search_text(name, combo))]
102+
return [
103+
(f"{name}-{i}", i)
104+
for i, combo in enumerate(itertools.product(*ids))
105+
if not case_filter or re.search(case_filter, _search_text(name, combo))
106+
]
104107

105108

106109
def matches_name_only(name, ids, case_filter) -> bool:

‎src/benchx/adapters/gbench.py‎

Lines changed: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,11 @@
4343

4444
def default_precision() -> dict:
4545
"""The precision a Google Benchmark order gets with nothing configured."""
46-
return {"repetitions": DEFAULT_REPETITIONS, "calibration": dict(DEFAULTS["calibration"]),
47-
"warmup": dict(DEFAULTS["warmup"])}
46+
return {
47+
"repetitions": DEFAULT_REPETITIONS,
48+
"calibration": dict(DEFAULTS["calibration"]),
49+
"warmup": dict(DEFAULTS["warmup"]),
50+
}
4851

4952

5053
def protocol(precision: dict) -> tuple[dict, list[str]]:
@@ -129,9 +132,14 @@ def list_cases(binary, case_filter, env, timeout=None) -> list[str]:
129132

130133
def run_case(binary, case, flags, env, timeout, native_path, env_names=(), harness_verbosity=0) -> dict:
131134
"""Run one case; never raises for harness failures, which become results."""
132-
args = [str(binary), f"--benchmark_filter=^{re.escape(case)}$",
133-
f"--benchmark_out={native_path}", "--benchmark_out_format=json", *flags,
134-
*([f"--v={harness_verbosity}"] if harness_verbosity else [])] # the library's own logging, on stderr
135+
args = [
136+
str(binary),
137+
f"--benchmark_filter=^{re.escape(case)}$",
138+
f"--benchmark_out={native_path}",
139+
"--benchmark_out_format=json",
140+
*flags,
141+
*([f"--v={harness_verbosity}"] if harness_verbosity else []),
142+
] # the library's own logging, on stderr
135143
note_case(logger, args, cwd=None, timeout=timeout)
136144
try:
137145
out = subprocess.run(args, env=env, capture_output=True, text=True, timeout=timeout)
@@ -147,8 +155,7 @@ def run_case(binary, case, flags, env, timeout, native_path, env_names=(), harne
147155
except ValueError:
148156
native = None
149157
note_case_ended(logger, status, timeout, native_path, parsed=native is not None)
150-
return {"exit_status": status, "timed_out": status is None, "stdout": stdout, "stderr": stderr,
151-
"native": native}
158+
return {"exit_status": status, "timed_out": status is None, "stdout": stdout, "stderr": stderr, "native": native}
152159

153160

154161
def translate(case: str, quantities: list[str], run: dict, attempted: int) -> list[dict]:
@@ -163,10 +170,17 @@ def translate(case: str, quantities: list[str], run: dict, attempted: int) -> li
163170

164171
if good and len(good) < attempted and not run["timed_out"]:
165172
first = (failed or skipped or [{}])[0]
166-
logger.warning("%s: %d of %d repetition(s) were not measured (%d errored, %d skipped)%s", case,
167-
attempted - len(good), attempted, len(failed), len(skipped),
168-
f"; the first said: {first.get('error_message') or first.get('skip_message')}"
169-
if first.get("error_message") or first.get("skip_message") else "")
173+
logger.warning(
174+
"%s: %d of %d repetition(s) were not measured (%d errored, %d skipped)%s",
175+
case,
176+
attempted - len(good),
177+
attempted,
178+
len(failed),
179+
len(skipped),
180+
f"; the first said: {first.get('error_message') or first.get('skip_message')}"
181+
if first.get("error_message") or first.get("skip_message")
182+
else "",
183+
)
170184
outputs = []
171185
for name in quantities:
172186
field, quantity = QUANTITIES[name]
@@ -197,8 +211,7 @@ def translate(case: str, quantities: list[str], run: dict, attempted: int) -> li
197211
info["iterations"] = [r.get("iterations") for r in good]
198212
if run["exit_status"] not in (0, None):
199213
info["exit_status"] = run["exit_status"]
200-
outputs.append({"quantity": quantity, "measurement": measurement,
201-
"procedure": procedure, "info": info})
214+
outputs.append({"quantity": quantity, "measurement": measurement, "procedure": procedure, "info": info})
202215
return outputs
203216

204217

@@ -211,8 +224,18 @@ def _summaries(aggregates: dict, field: str) -> list[dict]:
211224
continue
212225
value = row[field] * _TO_SECONDS[row.get("time_unit", "ns")]
213226
if summary_type == "estimate":
214-
summaries.append({"type": "estimate", "source": "producer", "value": value, "estimator": {
215-
"name": name, "method_version": f"google-benchmark/{name}", "input_level": "observations"}})
227+
summaries.append(
228+
{
229+
"type": "estimate",
230+
"source": "producer",
231+
"value": value,
232+
"estimator": {
233+
"name": name,
234+
"method_version": f"google-benchmark/{name}",
235+
"input_level": "observations",
236+
},
237+
}
238+
)
216239
else:
217240
summaries.append({"type": "statistic", "source": "producer", "name": name, "value": value})
218241
return summaries
@@ -224,6 +247,9 @@ def context_facts(native: dict | None) -> tuple[dict, dict]:
224247
§4.4); the harness's copy stays in the native artifact."""
225248
context = (native or {}).get("context", {})
226249
system = {"cpu": {"scaling_enabled": context["cpu_scaling_enabled"]}} if "cpu_scaling_enabled" in context else {}
227-
info = {k: context[k] for k in ("host_name", "num_cpus", "mhz_per_cpu", "executable",
228-
"library_build_type", "library_version", "date") if k in context}
250+
info = {
251+
k: context[k]
252+
for k in ("host_name", "num_cpus", "mhz_per_cpu", "executable", "library_build_type", "library_version", "date")
253+
if k in context
254+
}
229255
return system, info

0 commit comments

Comments
 (0)