| 1 |
#!/usr/bin/env python3 |
| 2 |
# Copyright: 2026, Maximiliano Curia <[email protected]> |
| 3 |
# |
| 4 |
# License: ISC |
| 5 |
# Permission to use, copy, modify, and/or distribute this software for any |
| 6 |
# purpose with or without fee is hereby granted, provided that the above |
| 7 |
# copyright notice and this permission notice appear in all copies. |
| 8 |
# . |
| 9 |
# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH |
| 10 |
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY |
| 11 |
# AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, |
| 12 |
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM |
| 13 |
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE |
| 14 |
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR |
| 15 |
# PERFORMANCE OF THIS SOFTWARE. |
| 16 |
|
| 17 |
"""Per-stage benchmark for the decopy file-processing pipeline. |
| 18 |
|
| 19 |
Reads a corpus once, then times each stage of decopy._process_content |
| 20 |
independently (read+decode, parse_holders, clean_comments, find_licenses) and |
| 21 |
reports seconds, ms/file and the share of total per-file CPU. Also runs a |
| 22 |
thread-scaling check on find_licenses, which exposes whether the `regex` |
| 23 |
backend lets the thread pool parallelise the dominant cost (today it does not: |
| 24 |
regex holds the GIL). |
| 25 |
|
| 26 |
This is the inner-loop tool for the performance work; pair it with the |
| 27 |
golden-output regression (tests/golden_output_test.py) so speedups are proven |
| 28 |
to preserve behaviour. |
| 29 |
|
| 30 |
Run from the repository root. The corpus defaults to the in-repo fixtures so it |
| 31 |
works with no external checkout; point it at a large tree for the real picture: |
| 32 |
|
| 33 |
python3 scripts/bench_pipeline.py |
| 34 |
python3 scripts/bench_pipeline.py ~/debian/python/ruff/crates --ext .rs,.py |
| 35 |
python3 scripts/bench_pipeline.py ~/debian/python/ruff --limit 4000 --json |
| 36 |
""" |
| 37 |
|
| 38 |
from __future__ import annotations |
| 39 |
|
| 40 |
import argparse |
| 41 |
import io |
| 42 |
import json |
| 43 |
import os |
| 44 |
import subprocess |
| 45 |
import sys |
| 46 |
import threading |
| 47 |
import time |
| 48 |
from pathlib import Path |
| 49 |
|
| 50 |
ROOT = Path(__file__).resolve().parent.parent |
| 51 |
sys.path.insert(0, str(ROOT)) |
| 52 |
|
| 53 |
from decopy.fstree.parsers import generic_input # noqa: E402 |
| 54 |
from decopy.licensing.holders import parse_holders # noqa: E402 |
| 55 |
from decopy.licensing.licenses import clean_comments, find_licenses # noqa: E402 |
| 56 |
|
| 57 |
|
| 58 |
def collect_files(root: Path, exts: set[str], limit: int) -> list[Path]: |
| 59 |
"""Regular, non-symlink files under root, optionally filtered by suffix.""" |
| 60 |
files: list[Path] = [] |
| 61 |
for path in sorted(root.rglob("*")): |
| 62 |
if not path.is_file() or path.is_symlink(): |
| 63 |
continue |
| 64 |
if exts and path.suffix not in exts: |
| 65 |
continue |
| 66 |
files.append(path) |
| 67 |
if limit and len(files) >= limit: |
| 68 |
break |
| 69 |
return files |
| 70 |
|
| 71 |
|
| 72 |
def read_corpus(files: list[Path]) -> tuple[list[str], float, int]: |
| 73 |
"""Read+decode every file the way decopy does; return texts, secs, bytes.""" |
| 74 |
texts: list[str] = [] |
| 75 |
total_bytes = 0 |
| 76 |
start = time.perf_counter() |
| 77 |
for path in files: |
| 78 |
try: |
| 79 |
raw = path.read_bytes() |
| 80 |
except OSError: |
| 81 |
continue |
| 82 |
total_bytes += len(raw) |
| 83 |
reader = io.BufferedReader(io.BytesIO(raw)) # type: ignore[arg-type] |
| 84 |
texts.append("".join(generic_input(reader))) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] |
| 85 |
return texts, time.perf_counter() - start, total_bytes |
| 86 |
|
| 87 |
|
| 88 |
def time_stage(label: str, fn, items: list) -> tuple[str, float]: # noqa: ANN001 |
| 89 |
start = time.perf_counter() |
| 90 |
for item in items: |
| 91 |
fn(item) |
| 92 |
return label, time.perf_counter() - start |
| 93 |
|
| 94 |
|
| 95 |
def measure_import_cost() -> float: |
| 96 |
"""Time a fresh import of decopy.licensing.res (compiles all license patterns).""" |
| 97 |
code = ( |
| 98 |
"import time; t=time.perf_counter(); " |
| 99 |
"import decopy.licensing.res; print(time.perf_counter()-t)" |
| 100 |
) |
| 101 |
env = {**os.environ, "PYTHONPATH": str(ROOT)} |
| 102 |
try: |
| 103 |
out = subprocess.run( # noqa: S603 |
| 104 |
[sys.executable, "-c", code], |
| 105 |
check=True, |
| 106 |
capture_output=True, |
| 107 |
text=True, |
| 108 |
env=env, |
| 109 |
) |
| 110 |
return float(out.stdout.strip()) |
| 111 |
except (subprocess.CalledProcessError, ValueError): |
| 112 |
return float("nan") |
| 113 |
|
| 114 |
|
| 115 |
def thread_scaling(cleaned: list[str], thread_counts: list[int]) -> list[dict]: |
| 116 |
"""Run find_licenses over the corpus on N threads; report wall time.""" |
| 117 |
|
| 118 |
def worker(chunk: list[str]) -> None: |
| 119 |
for text in chunk: |
| 120 |
list(find_licenses(text)) |
| 121 |
|
| 122 |
results = [] |
| 123 |
base = None |
| 124 |
for n in thread_counts: |
| 125 |
chunks = [cleaned[i::n] for i in range(n)] |
| 126 |
start = time.perf_counter() |
| 127 |
threads = [threading.Thread(target=worker, args=(c,)) for c in chunks] |
| 128 |
for thread in threads: |
| 129 |
thread.start() |
| 130 |
for thread in threads: |
| 131 |
thread.join() |
| 132 |
elapsed = time.perf_counter() - start |
| 133 |
if base is None: |
| 134 |
base = elapsed |
| 135 |
results.append({"threads": n, "seconds": elapsed, "speedup": base / elapsed}) |
| 136 |
return results |
| 137 |
|
| 138 |
|
| 139 |
def run(args: argparse.Namespace) -> dict: |
| 140 |
exts = {e if e.startswith(".") else f".{e}" for e in args.ext.split(",") if e} |
| 141 |
files = collect_files(Path(args.corpus), exts, args.limit) |
| 142 |
if not files: |
| 143 |
print(f"No files under {args.corpus}", file=sys.stderr) |
| 144 |
raise SystemExit(2) |
| 145 |
|
| 146 |
texts, read_secs, total_bytes = read_corpus(files) |
| 147 |
n = len(texts) |
| 148 |
cleaned = [clean_comments(t) for t in texts] |
| 149 |
|
| 150 |
stages = [ |
| 151 |
("read+decode", read_secs), |
| 152 |
time_stage("parse_holders", parse_holders, texts), |
| 153 |
time_stage("clean_comments", clean_comments, texts), |
| 154 |
time_stage("find_licenses", lambda t: list(find_licenses(t)), cleaned), |
| 155 |
] |
| 156 |
process_total = sum(s for label, s in stages if label != "read+decode") |
| 157 |
|
| 158 |
max_threads = min(8, (os.cpu_count() or 1)) |
| 159 |
thread_counts = [c for c in (1, 2, 4, 8) if c <= max_threads] or [1] |
| 160 |
|
| 161 |
return { |
| 162 |
"corpus": str(args.corpus), |
| 163 |
"files": n, |
| 164 |
"megabytes": round(total_bytes / 1e6, 2), |
| 165 |
"import_compile_seconds": round(measure_import_cost(), 3), |
| 166 |
"stages": [ |
| 167 |
{ |
| 168 |
"stage": label, |
| 169 |
"seconds": round(secs, 3), |
| 170 |
"ms_per_file": round(1000 * secs / n, 3), |
| 171 |
"share_pct": ( |
| 172 |
round(100 * secs / process_total, 1) |
| 173 |
if label != "read+decode" and process_total |
| 174 |
else None |
| 175 |
), |
| 176 |
} |
| 177 |
for label, secs in stages |
| 178 |
], |
| 179 |
"process_total_seconds": round(process_total, 3), |
| 180 |
"thread_scaling_find_licenses": thread_scaling(cleaned, thread_counts), |
| 181 |
"cpu_count": os.cpu_count(), |
| 182 |
} |
| 183 |
|
| 184 |
|
| 185 |
def print_report(report: dict) -> None: |
| 186 |
print(f"corpus: {report['corpus']}") |
| 187 |
print( |
| 188 |
f"files: {report['files']} size: {report['megabytes']} MB " |
| 189 |
f"cpus: {report['cpu_count']} " |
| 190 |
f"import+compile: {report['import_compile_seconds']}s (one-time)" |
| 191 |
) |
| 192 |
print(f"\n{'stage':<16}{'seconds':>10}{'ms/file':>10}{'share':>8}") |
| 193 |
for stage in report["stages"]: |
| 194 |
share = "" if stage["share_pct"] is None else f"{stage['share_pct']}%" |
| 195 |
print( |
| 196 |
f"{stage['stage']:<16}{stage['seconds']:>10}" |
| 197 |
f"{stage['ms_per_file']:>10}{share:>8}" |
| 198 |
) |
| 199 |
print(f"{'(process total)':<16}{report['process_total_seconds']:>10}") |
| 200 |
print("\nfind_licenses thread scaling (regex holds the GIL -> expect ~1x):") |
| 201 |
for row in report["thread_scaling_find_licenses"]: |
| 202 |
print( |
| 203 |
f" {row['threads']:>2} threads: {row['seconds']:.3f}s " |
| 204 |
f"speedup {row['speedup']:.2f}x" |
| 205 |
) |
| 206 |
|
| 207 |
|
| 208 |
def main() -> int: |
| 209 |
parser = argparse.ArgumentParser(description=__doc__) |
| 210 |
parser.add_argument( |
| 211 |
"corpus", |
| 212 |
nargs="?", |
| 213 |
default=str(ROOT / "tests" / "testdata"), |
| 214 |
help="directory to scan (default: in-repo fixtures)", |
| 215 |
) |
| 216 |
parser.add_argument( |
| 217 |
"--ext", |
| 218 |
default="", |
| 219 |
help="comma-separated suffix filter, e.g. .rs,.py (default: all files)", |
| 220 |
) |
| 221 |
parser.add_argument( |
| 222 |
"--limit", type=int, default=0, help="cap number of files (0 = no cap)" |
| 223 |
) |
| 224 |
parser.add_argument("--json", action="store_true", help="emit the report as JSON") |
| 225 |
args = parser.parse_args() |
| 226 |
|
| 227 |
report = run(args) |
| 228 |
if args.json: |
| 229 |
print(json.dumps(report, indent=2)) |
| 230 |
else: |
| 231 |
print_report(report) |
| 232 |
return 0 |
| 233 |
|
| 234 |
|
| 235 |
if __name__ == "__main__": |
| 236 |
sys.exit(main()) |