Skip to content

Commit

Permalink
add benchmark for class / method calls
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Mar 29, 2024
1 parent cf74624 commit 60ef9dc
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion pyo3-benches/benches/bench_pyclass.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{impl_::pyclass::LazyTypeObject, prelude::*};
use pyo3::{impl_::pyclass::LazyTypeObject, intern, prelude::*};

/// This is a feature-rich class instance used to benchmark various parts of the pyclass lifecycle.
#[pyclass]
Expand All @@ -15,6 +15,12 @@ impl MyClass {
Self { elements }
}

fn method_call(&self) {}

fn __len__(&self) -> usize {
self.elements.len()
}

fn __call__(&mut self, new_element: i32) -> usize {
self.elements.push(new_element);
self.elements.len()
Expand All @@ -37,8 +43,24 @@ pub fn first_time_init(b: &mut Bencher<'_>) {
});
}

pub fn method_call(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj = Bound::new(py, MyClass::new(vec![])).unwrap();
b.iter(|| obj.call_method0(intern!(py, "method_call")));
});
}

pub fn proto_call(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj = Bound::new(py, MyClass::new(vec![])).unwrap();
b.iter(|| obj.len());
});
}

fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("first_time_init", first_time_init);
c.bench_function("method_call", method_call);
c.bench_function("proto_call", proto_call);
}

criterion_group!(benches, criterion_benchmark);
Expand Down

0 comments on commit 60ef9dc

Please sign in to comment.