From 0cc77c77b2bfcd20ff0a137dccf5ce80ca06d5f5 Mon Sep 17 00:00:00 2001 From: David Hewitt <1939362+davidhewitt@users.noreply.github.com> Date: Sun, 16 May 2021 08:11:37 +0100 Subject: [PATCH] benches: add bench_gil --- Cargo.toml | 7 ++++++- benches/bench_gil.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 benches/bench_gil.rs diff --git a/Cargo.toml b/Cargo.toml index 533b816b565..6dcc5d2d02d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ serde = {version = "1.0", optional = true} [dev-dependencies] assert_approx_eq = "1.1.0" +criterion = "0.3" trybuild = "1.0.23" rustversion = "1.0" proptest = { version = "0.10.1", default-features = false, features = ["std"] } @@ -69,6 +70,10 @@ auto-initialize = [] # Optimizes PyObject to Vec conversion and so on. nightly = [] +[[bench]] +name = "bench_gil" +harness = false + [workspace] members = [ "pyo3-macros", @@ -83,4 +88,4 @@ members = [ [package.metadata.docs.rs] no-default-features = true features = ["macros", "num-bigint", "num-complex", "hashbrown", "serde", "multiple-pymethods"] -rustdoc-args = ["--cfg", "docsrs"] \ No newline at end of file +rustdoc-args = ["--cfg", "docsrs"] diff --git a/benches/bench_gil.rs b/benches/bench_gil.rs new file mode 100644 index 00000000000..8dfed873a45 --- /dev/null +++ b/benches/bench_gil.rs @@ -0,0 +1,41 @@ +use criterion::{criterion_group, criterion_main, BatchSize, Bencher, Criterion}; + +use pyo3::{prelude::*, GILPool}; + +fn bench_clean_gilpool_new(b: &mut Bencher) { + Python::with_gil(|_py| { + b.iter(|| { + let _ = unsafe { GILPool::new() }; + }); + }); +} + +fn bench_clean_acquire_gil(b: &mut Bencher) { + // Acquiring first GIL will also create a "clean" GILPool, so this measures the Python overhead. + b.iter(|| { + let _ = Python::acquire_gil(); + }); +} + +fn bench_dirty_acquire_gil(b: &mut Bencher) { + let obj = Python::with_gil(|py| py.None()); + b.iter_batched( + || { + // Clone and drop an object so that the GILPool has work to do. + let _ = obj.clone(); + }, + |_| { + let _ = Python::acquire_gil(); + }, + BatchSize::NumBatches(1), + ); +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("clean_gilpool_new", bench_clean_gilpool_new); + c.bench_function("clean_acquire_gil", bench_clean_acquire_gil); + c.bench_function("dirty_acquire_gil", bench_dirty_acquire_gil); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches);