Skip to content

Commit 7c79b54

Browse files
committed
Add an improved Rust version that iterates chars just once
---------------------------------------------------------------------------------------- Name (time in us) Min Max Mean ---------------------------------------------------------------------------------------- test_rust_once 694.0350 (1.0) 741.8010 (1.0) 695.5648 (1.0) test_rust 1,806.4040 (2.60) 1,935.9130 (2.61) 1,812.6250 (2.61) test_regex 14,219.5200 (20.49) 14,421.8970 (19.44) 14,244.1962 (20.48) test_pure_python 31,766.5810 (45.77) 52,128.1230 (70.27) 35,289.6043 (50.74) ----------------------------------------------------------------------------------------
1 parent 7da1b03 commit 7c79b54

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

doubles_with_rust.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,6 @@ def test_regex(benchmark):
3232

3333
def test_rust(benchmark):
3434
benchmark(myrustlib.count_doubles, val)
35+
36+
def test_rust_once(benchmark):
37+
benchmark(myrustlib.count_doubles_once, val)

pyext-myrustlib/src/lib.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,25 @@ fn count_doubles(_py: Python, val: &str) -> PyResult<u64> {
1515
Ok(total)
1616
}
1717

18+
fn count_doubles_once(_py: Python, val: &str) -> PyResult<u64> {
19+
let mut total = 0u64;
20+
21+
let mut chars = val.chars();
22+
if let Some(mut c1) = chars.next() {
23+
for c2 in chars {
24+
if c1 == c2 {
25+
total += 1;
26+
}
27+
c1 = c2;
28+
}
29+
}
30+
31+
Ok(total)
32+
}
33+
1834
py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | {
1935
try!(m.add(py, "__doc__", "This module is implemented in Rust"));
2036
try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str))));
37+
try!(m.add(py, "count_doubles_once", py_fn!(py, count_doubles_once(val: &str))));
2138
Ok(())
2239
});

0 commit comments

Comments
 (0)