-
Notifications
You must be signed in to change notification settings - Fork 804
/
Copy pathbench_any.rs
94 lines (84 loc) · 2.46 KB
/
bench_any.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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,
};
#[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() {
ObjectType::None
} else if obj.is_instance_of::<PyBool>() {
ObjectType::Bool
} else if obj.is_instance_of::<PyByteArray>() {
ObjectType::ByteArray
} else if obj.is_instance_of::<PyBytes>() {
ObjectType::Bytes
} else if obj.is_instance_of::<PyDict>() {
ObjectType::Dict
} else if obj.is_instance_of::<PyFloat>() {
ObjectType::Float
} else if obj.is_instance_of::<PyFrozenSet>() {
ObjectType::FrozenSet
} else if obj.is_instance_of::<PyInt>() {
ObjectType::Int
} else if obj.is_instance_of::<PyList>() {
ObjectType::List
} else if obj.is_instance_of::<PySet>() {
ObjectType::Set
} else if obj.is_instance_of::<PyString>() {
ObjectType::Str
} else if obj.is_instance_of::<PyTuple>() {
ObjectType::Tuple
} else if obj.downcast::<PySequence>().is_ok() {
ObjectType::Sequence
} else if obj.downcast::<PyMapping>().is_ok() {
ObjectType::Mapping
} else {
ObjectType::Unknown
}
}
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));
assert_eq!(find_object_type(obj), ObjectType::Unknown);
});
}
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()
});
});
}
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);
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);