From 7de13b496b030ab0fc5765e8482dd499ff9340ff Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 16 Feb 2026 08:47:32 -0700 Subject: [PATCH 1/2] ci: expand pyclass benchmarks --- pyo3-benches/benches/bench_pyclass.rs | 47 +++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/pyo3-benches/benches/bench_pyclass.rs b/pyo3-benches/benches/bench_pyclass.rs index 0967a897649..b951f162d4b 100644 --- a/pyo3-benches/benches/bench_pyclass.rs +++ b/pyo3-benches/benches/bench_pyclass.rs @@ -1,4 +1,6 @@ -use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion}; +use codspeed_criterion_compat::{criterion_group, criterion_main, BatchSize, Bencher, Criterion}; +use pyo3::conversion::IntoPyObjectExt; +use pyo3::types::PyInt; use pyo3::{impl_::pyclass::LazyTypeObject, prelude::*}; /// This is a feature-rich class instance used to benchmark various parts of the pyclass lifecycle. @@ -37,10 +39,49 @@ pub fn first_time_init(b: &mut Bencher<'_>) { }); } -fn criterion_benchmark(c: &mut Criterion) { +pub fn bench_pyclass(c: &mut Criterion) { + c.bench_function("bench_pyclass_create", |b| { + Python::attach(|py| { + b.iter_batched( + || vec![1, 2, 3], + |elements| { + MyClass::new(elements).into_py_any(py).unwrap(); + }, + BatchSize::SmallInput, + ); + }); + }); + c.bench_function("bench_call", |b| { + Python::attach(|py| { + b.iter_batched( + || { + ( + MyClass::new(vec![1, 2, 3]).into_py_any(py).unwrap(), + PyInt::new(py, 4), + ) + }, + |(inst, arg)| { + inst.call1(py, (arg,)).unwrap(); + }, + BatchSize::SmallInput, + ); + }); + }); + c.bench_function("bench_str", |b| { + Python::attach(|py| { + b.iter_batched( + || MyClass::new(vec![1, 2, 3]).into_py_any(py).unwrap(), + |inst| inst.bind(py).str(), + BatchSize::SmallInput, + ); + }); + }); +} + +fn bench_first_time_init(c: &mut Criterion) { c.bench_function("first_time_init", first_time_init); } -criterion_group!(benches, criterion_benchmark); +criterion_group!(benches, bench_first_time_init, bench_pyclass); criterion_main!(benches); From 48537e680209f1fd49254101535119f54b050d84 Mon Sep 17 00:00:00 2001 From: Nathan Goldbaum Date: Mon, 16 Feb 2026 09:47:15 -0700 Subject: [PATCH 2/2] fix resource issue in bench_str --- pyo3-benches/benches/bench_pyclass.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/pyo3-benches/benches/bench_pyclass.rs b/pyo3-benches/benches/bench_pyclass.rs index b951f162d4b..f2a4a0f6747 100644 --- a/pyo3-benches/benches/bench_pyclass.rs +++ b/pyo3-benches/benches/bench_pyclass.rs @@ -69,11 +69,9 @@ pub fn bench_pyclass(c: &mut Criterion) { }); c.bench_function("bench_str", |b| { Python::attach(|py| { - b.iter_batched( - || MyClass::new(vec![1, 2, 3]).into_py_any(py).unwrap(), - |inst| inst.bind(py).str(), - BatchSize::SmallInput, - ); + let inst = MyClass::new(vec![1, 2, 3]).into_py_any(py).unwrap(); + let bound = inst.bind(py); + b.iter(|| bound.str()); }); }); }