pyo3/benches/bench_any.rs

95 lines
2.5 KiB
Rust
Raw Normal View History

2023-01-15 09:54:20 +00:00
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use pyo3::{
types::{
PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyMapping,
PySequence, PySet, PyString, PyTuple,
},
PyAny, PyResult, Python,
2023-01-15 09:54:20 +00:00
};
#[derive(PartialEq, Eq, Debug)]
enum ObjectType {
None,
Bool,
ByteArray,
Bytes,
Dict,
Float,
FrozenSet,
Int,
List,
Set,
Str,
Tuple,
Sequence,
Mapping,
Unknown,
}
fn find_object_type(obj: &PyAny) -> ObjectType {
if obj.is_none() {
2023-01-15 09:54:20 +00:00
ObjectType::None
} else if obj.is_instance_of::<PyBool>() {
2023-01-15 09:54:20 +00:00
ObjectType::Bool
} else if obj.is_instance_of::<PyByteArray>() {
2023-01-15 09:54:20 +00:00
ObjectType::ByteArray
} else if obj.is_instance_of::<PyBytes>() {
2023-01-15 09:54:20 +00:00
ObjectType::Bytes
} else if obj.is_instance_of::<PyDict>() {
2023-01-15 09:54:20 +00:00
ObjectType::Dict
} else if obj.is_instance_of::<PyFloat>() {
2023-01-15 09:54:20 +00:00
ObjectType::Float
} else if obj.is_instance_of::<PyFrozenSet>() {
2023-01-15 09:54:20 +00:00
ObjectType::FrozenSet
} else if obj.is_instance_of::<PyInt>() {
2023-01-15 09:54:20 +00:00
ObjectType::Int
} else if obj.is_instance_of::<PyList>() {
2023-01-15 09:54:20 +00:00
ObjectType::List
} else if obj.is_instance_of::<PySet>() {
2023-01-15 09:54:20 +00:00
ObjectType::Set
} else if obj.is_instance_of::<PyString>() {
2023-01-15 09:54:20 +00:00
ObjectType::Str
} else if obj.is_instance_of::<PyTuple>() {
2023-01-15 09:54:20 +00:00
ObjectType::Tuple
} else if obj.downcast::<PySequence>().is_ok() {
ObjectType::Sequence
} else if obj.downcast::<PyMapping>().is_ok() {
ObjectType::Mapping
} else {
ObjectType::Unknown
}
2023-01-15 09:54:20 +00:00
}
fn bench_identify_object_type(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let obj = py.eval("object()", None, None).unwrap();
b.iter(|| find_object_type(obj));
2023-01-15 09:54:20 +00:00
assert_eq!(find_object_type(obj), ObjectType::Unknown);
2023-01-15 09:54:20 +00:00
});
}
fn bench_collect_generic_iterator(b: &mut Bencher<'_>) {
Python::with_gil(|py| {
let collection = py.eval("list(range(1 << 20))", None, None).unwrap();
b.iter(|| {
collection
.iter()
.unwrap()
.collect::<PyResult<Vec<_>>>()
.unwrap()
});
});
}
2023-01-15 09:54:20 +00:00
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("identify_object_type", bench_identify_object_type);
c.bench_function("collect_generic_iterator", bench_collect_generic_iterator);
2023-01-15 09:54:20 +00:00
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);