Skip to content

Commit 4063a6a

Browse files
committed
benchmark startswith
1 parent 769bf99 commit 4063a6a

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

benches/main.rs

+62-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate test;
44
extern crate core;
55

66
use test::{black_box, Bencher};
7-
use pyo3::{AsPyPointer, ToBorrowedObject};
7+
use pyo3::{AsPyPointer, intern, ToBorrowedObject};
88
use pyo3::ffi;
99
use pyo3::prelude::*;
1010
use pyo3::types::{PyBool, PyDict, PyList, PySet, PyString};
@@ -269,3 +269,64 @@ fn isinstance_bool_type_is(bench: &mut Bencher) {
269269
});
270270
}
271271

272+
fn run_startswith_py(items: &PyList) -> PyResult<i32> {
273+
let mut count = 0;
274+
let startswith_pys = intern!(items.py(), "startswith");
275+
let underscore_pys = intern!(items.py(), "_");
276+
for item in items.iter() {
277+
let startswith_func = item.cast_as::<PyString>()?.getattr(startswith_pys)?;
278+
if startswith_func.call1((underscore_pys,))?.is_true()? {
279+
count += 1;
280+
}
281+
}
282+
Ok(count)
283+
}
284+
285+
#[bench]
286+
fn startswith_py(bench: &mut Bencher) {
287+
let gil = Python::acquire_gil();
288+
let py = gil.python();
289+
let items: Vec<PyObject> = (0..100).map(|i| {
290+
if i % 2 == 0 {
291+
i.to_string().to_object(py)
292+
} else {
293+
format!("_{}", i).to_object(py)
294+
}
295+
}).collect();
296+
let py_list = PyList::new(py, &items);
297+
assert_eq!(run_startswith_py(py_list).unwrap(), 50);
298+
299+
bench.iter(|| {
300+
black_box(run_startswith_py(py_list).unwrap());
301+
});
302+
}
303+
304+
fn run_startswith_rust(items: &PyList) -> PyResult<i32> {
305+
let mut count = 0;
306+
for item in items.iter() {
307+
let item_cow = item.cast_as::<PyString>()?.to_string_lossy();
308+
if item_cow.as_ref().starts_with('_') {
309+
count += 1;
310+
}
311+
}
312+
Ok(count)
313+
}
314+
315+
#[bench]
316+
fn startswith_rust(bench: &mut Bencher) {
317+
let gil = Python::acquire_gil();
318+
let py = gil.python();
319+
let items: Vec<PyObject> = (0..100).map(|i| {
320+
if i % 2 == 0 {
321+
i.to_string().to_object(py)
322+
} else {
323+
format!("_{}", i).to_object(py)
324+
}
325+
}).collect();
326+
let py_list = PyList::new(py, &items);
327+
assert_eq!(run_startswith_rust(py_list).unwrap(), 50);
328+
329+
bench.iter(|| {
330+
black_box(run_startswith_rust(py_list).unwrap());
331+
});
332+
}

0 commit comments

Comments
 (0)