pyo3/pyo3-benches/benches/bench_list.rs

77 lines
2.1 KiB
Rust
Raw Normal View History

use std::hint::black_box;
2023-08-29 06:26:36 +00:00
use codspeed_criterion_compat::{criterion_group, criterion_main, Bencher, Criterion};
2020-05-02 22:17:21 +00:00
use pyo3::prelude::*;
use pyo3::types::{PyList, PySequence};
2020-05-02 22:17:21 +00:00
2022-03-23 07:07:28 +00:00
fn iter_list(b: &mut Bencher<'_>) {
2022-07-19 17:34:23 +00:00
Python::with_gil(|py| {
const LEN: usize = 100_000;
2024-01-23 08:39:19 +00:00
let list = PyList::new_bound(py, 0..LEN);
2022-07-19 17:34:23 +00:00
let mut sum = 0;
b.iter(|| {
for x in &list {
2022-07-19 17:34:23 +00:00
let i: u64 = x.extract().unwrap();
sum += i;
}
});
2020-05-02 22:17:21 +00:00
});
}
2022-03-23 07:07:28 +00:00
fn list_new(b: &mut Bencher<'_>) {
2022-07-19 17:34:23 +00:00
Python::with_gil(|py| {
const LEN: usize = 50_000;
2024-01-23 08:44:47 +00:00
b.iter_with_large_drop(|| PyList::new_bound(py, 0..LEN));
2022-07-19 17:34:23 +00:00
});
}
2022-03-23 07:07:28 +00:00
fn list_get_item(b: &mut Bencher<'_>) {
2022-07-19 17:34:23 +00:00
Python::with_gil(|py| {
const LEN: usize = 50_000;
2024-01-23 08:39:19 +00:00
let list = PyList::new_bound(py, 0..LEN);
2022-07-19 17:34:23 +00:00
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
sum += list.get_item(i).unwrap().extract::<usize>().unwrap();
}
});
});
}
2021-08-30 08:13:43 +00:00
#[cfg(not(Py_LIMITED_API))]
2022-03-23 07:07:28 +00:00
fn list_get_item_unchecked(b: &mut Bencher<'_>) {
2022-07-19 17:34:23 +00:00
Python::with_gil(|py| {
const LEN: usize = 50_000;
2024-01-23 08:39:19 +00:00
let list = PyList::new_bound(py, 0..LEN);
2022-07-19 17:34:23 +00:00
let mut sum = 0;
b.iter(|| {
for i in 0..LEN {
unsafe {
sum += list.get_item_unchecked(i).extract::<usize>().unwrap();
}
}
2022-07-19 17:34:23 +00:00
});
2020-05-02 22:17:21 +00:00
});
}
2021-05-26 06:25:00 +00:00
fn sequence_from_list(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
const LEN: usize = 50_000;
let list = &PyList::new_bound(py, 0..LEN);
b.iter(|| black_box(list).downcast::<PySequence>().unwrap());
});
}
2021-05-26 06:25:00 +00:00
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("iter_list", iter_list);
c.bench_function("list_new", list_new);
2021-05-26 06:25:00 +00:00
c.bench_function("list_get_item", list_get_item);
2021-08-30 08:13:43 +00:00
#[cfg(not(Py_LIMITED_API))]
c.bench_function("list_get_item_unchecked", list_get_item_unchecked);
c.bench_function("sequence_from_list", sequence_from_list);
2021-05-26 06:25:00 +00:00
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);