diff --git a/batch_test.py b/batch_test.py new file mode 100644 index 0000000..e7e2cfe --- /dev/null +++ b/batch_test.py @@ -0,0 +1,24 @@ +import random + +import pytest + +import unit_converter + + +@pytest.fixture(scope="module") +def batch_numbers(): + return [random.random() * 100 for x in range(1000)] + # The larger the range of numbers, the closer the Rust version is to Python. + # e.g. return [random.random() * 100 for x in range(1000000)] + + +def batch_python_unit_converter(temperatures): + return [celsius * 1.8 + 32.0 for celsius in temperatures] + + +def test_using_python_batch(benchmark, batch_numbers): + benchmark(batch_python_unit_converter, batch_numbers) + + +def test_using_rust_batch(benchmark, batch_numbers): + benchmark(unit_converter.batch_convert_celsius_to_fahrenheit, batch_numbers) diff --git a/src/lib.rs b/src/lib.rs index 3dfee57..e9dc080 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,19 +1,27 @@ #![feature(specialization)] -#[macro_use] extern crate pyo3; +#[macro_use] +extern crate pyo3; use pyo3::prelude::*; - #[pyfunction] fn convert_celsius_to_fahrenheit(celsius: f32) -> f32 { celsius * 1.8 + 32.0 } +#[pyfunction] +fn batch_convert_celsius_to_fahrenheit(celsius: Vec) -> Vec { + celsius + .iter() + .map(|temperature| convert_celsius_to_fahrenheit(temperature.clone())) + .collect() +} + #[pymodule] fn unit_converter(_py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(convert_celsius_to_fahrenheit))?; - + m.add_wrapped(wrap_pyfunction!(batch_convert_celsius_to_fahrenheit))?; Ok(()) } diff --git a/test.py b/test.py index b9c09fd..05191e0 100644 --- a/test.py +++ b/test.py @@ -7,6 +7,10 @@ def python_unit_converter(celsius): return celsius * 1.8 + 32.0 +def batch_python_unit_converter(temperatures): + return [celsius * 1.8 + 32.0 for celsius in temperatures] + + def test_using_unit_converter(): assert unit_converter.convert_celsius_to_fahrenheit(25.0) == 77.0 assert python_unit_converter(25.0) == 77.0