Skip to content

Commit e3ceec7

Browse files
committed
Fix benchmark execution and library dependency reports
Assisted-by: Codex:GPT-6
1 parent 657bab3 commit e3ceec7

5 files changed

Lines changed: 61 additions & 33 deletions

File tree

‎benches/README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ in two ways:
5757
Execution includes compilation and runs each iteration with a fresh namespace whose `__name__`
5858
is `"__main__"`, so script entry points run in both RustPython and CPython.
5959

60+
Both Rust harnesses load only `.py` files and run workloads in filename order.
61+
Other entries, such as `__pycache__` directories, are ignored.
62+
6063
### Adding a micro benchmark
6164

6265
Micro benchmarks are small snippets of code added under the `microbenchmarks/` directory. A microbenchmark file has
@@ -85,6 +88,21 @@ obj = [i for i in range(ITERATIONS)]
8588

8689
`ITERATIONS` can appear in both the setup code and the benchmark code.
8790

91+
## Subprocess benchmarks with pytest
92+
93+
The optional pytest driver measures whole interpreter processes, including startup.
94+
Install `pytest` and `pytest-benchmark`, build RustPython with `cargo build --release`,
95+
and run from the repository root:
96+
97+
```shell
98+
python -m pytest benches/test_benchmarks.py
99+
```
100+
101+
It uses the release executable in `target/release` by default. Set `RUSTPYTHON` to
102+
the executable path when using a different build directory. Script paths are
103+
resolved relative to this checkout, so pytest can also be launched from another
104+
directory. A failed subprocess fails the benchmark instead of producing a timing.
105+
88106
## MacOS setup
89107

90108
On MacOS you will need to add the following to a `.cargo/config` file:

‎benches/execution.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
#![allow(clippy::iter_over_hash_type)]
2-
31
extern crate alloc;
42

3+
use alloc::collections::BTreeMap;
54
use core::hint::black_box;
65
use criterion::{
76
Bencher, BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
@@ -10,7 +9,7 @@ use criterion::{
109
use pyo3::types::{PyCode, PyCodeMethods, PyDict, PyDictMethods, code::PyCodeInput};
1110
use rustpython_compiler::Mode;
1211
use rustpython_vm::{Interpreter, PyResult, Settings};
13-
use std::{collections::HashMap, path::Path};
12+
use std::path::Path;
1413

1514
/// `true` when the benchmarks are executed by the CodSpeed runner.
1615
///
@@ -130,14 +129,15 @@ pub fn criterion_benchmark(c: &mut Criterion) {
130129
let mut benches = benchmark_dir
131130
.read_dir()
132131
.unwrap()
133-
.map(|entry| {
134-
let path = entry.unwrap().path();
132+
.map(|entry| entry.unwrap().path())
133+
.filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py"))
134+
.map(|path| {
135135
(
136136
path.file_name().unwrap().to_str().unwrap().to_owned(),
137137
std::fs::read_to_string(path).unwrap(),
138138
)
139139
})
140-
.collect::<HashMap<_, _>>();
140+
.collect::<BTreeMap<_, _>>();
141141

142142
// Benchmark parsing
143143
let mut parse_group = c.benchmark_group("parse_to_ast");

‎benches/microbenchmarks.rs‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,16 +207,20 @@ pub fn run_micro_benchmark(c: &mut Criterion, benchmark: MicroBenchmark) {
207207

208208
pub fn criterion_benchmark(c: &mut Criterion) {
209209
let benchmark_dir = Path::new("./benches/microbenchmarks/");
210-
let dirs: Vec<fs::DirEntry> = benchmark_dir
210+
let mut paths: Vec<_> = benchmark_dir
211211
.read_dir()
212212
.unwrap()
213-
.collect::<io::Result<_>>()
214-
.unwrap();
213+
.collect::<io::Result<Vec<_>>>()
214+
.unwrap()
215+
.into_iter()
216+
.map(|entry| entry.path())
217+
.filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py"))
218+
.collect();
219+
paths.sort();
215220

216-
let benchmarks: Vec<MicroBenchmark> = dirs
221+
let benchmarks: Vec<MicroBenchmark> = paths
217222
.iter()
218-
.map(|d| {
219-
let p = d.path();
223+
.map(|p| {
220224
let name = p.file_name().unwrap().to_os_string();
221225
let contents = fs::read_to_string(p).unwrap();
222226
let iterate = contents.contains("ITERATIONS");

‎benches/test_benchmarks.py‎

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,36 @@
1-
21
import os
3-
import time
2+
import subprocess
43
import sys
4+
from pathlib import Path
55

66
import pytest
7-
import subprocess
7+
8+
ROOT = Path(__file__).resolve().parent.parent
9+
BENCHES = ROOT / "benches"
810

911
# Interpreters:
10-
rustpython_exe = '../target/release/rustpython'
12+
default_rustpython = (
13+
ROOT
14+
/ "target"
15+
/ "release"
16+
/ ("rustpython.exe" if os.name == "nt" else "rustpython")
17+
)
18+
rustpython_exe = str(Path(os.environ.get("RUSTPYTHON", default_rustpython)).resolve())
1119
cpython_exe = sys.executable
12-
pythons = [
13-
cpython_exe,
14-
rustpython_exe
15-
]
20+
pythons = [cpython_exe, rustpython_exe]
1621

1722
# Benchmark scripts:
1823
benchmarks = [
19-
['benchmarks/nbody.py'],
20-
['benchmarks/mandelbrot.py'],
21-
['benchmarks/strings.py'],
24+
BENCHES / "benchmarks" / "nbody.py",
25+
BENCHES / "benchmarks" / "mandelbrot.py",
26+
BENCHES / "microbenchmarks" / "strings.py",
2227
]
2328

24-
exe_ids = ['cpython', 'rustpython']
25-
benchmark_ids = [benchmark[0].split('/')[-1] for benchmark in benchmarks]
26-
27-
@pytest.mark.parametrize('exe', pythons, ids=exe_ids)
28-
@pytest.mark.parametrize('args', benchmarks, ids=benchmark_ids)
29-
def test_bench(exe, args, benchmark):
30-
def bench():
31-
subprocess.run([exe] + args)
29+
exe_ids = ["cpython", "rustpython"]
30+
benchmark_ids = [benchmark.name for benchmark in benchmarks]
3231

33-
benchmark(bench)
3432

33+
@pytest.mark.parametrize("exe", pythons, ids=exe_ids)
34+
@pytest.mark.parametrize("script", benchmarks, ids=benchmark_ids)
35+
def test_bench(exe, script, benchmark):
36+
benchmark(subprocess.run, [exe, str(script)], cwd=ROOT, check=True)

‎scripts/update_lib/file_utils.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import ast
1616
import filecmp
1717
import pathlib
18+
import warnings
1819
from collections.abc import Callable, Iterator
1920

2021
# === I/O utilities ===
@@ -31,7 +32,10 @@ def safe_read_text(path: pathlib.Path) -> str | None:
3132
def safe_parse_ast(content: str) -> ast.Module | None:
3233
"""Parse Python content into AST, returning None on syntax error."""
3334
try:
34-
return ast.parse(content)
35+
# Test fixtures may deliberately contain syntax that emits warnings.
36+
with warnings.catch_warnings():
37+
warnings.simplefilter("ignore", SyntaxWarning)
38+
return ast.parse(content)
3539
except SyntaxError:
3640
return None
3741

0 commit comments

Comments
 (0)