FAQ - Help and questions

How do I move a slow Python function to Rust with PyO3?

#python#pyo3#performancepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Write the function in Rust, mark it with the pyfunction attribute, build the crate as a cdylib and import it like any Python module; maturin automates the build and the packaging. Move only the hot function, check that it returns the same results, and time both versions on your own data.

Checked with rustc 1.93.0, pyo3 0.24.2, Python 3.13.7, Windows 11 (built with cargo; maturin was not run)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

PyO3 is a Rust library that lets Rust code define Python modules, functions and classes. The Python side sees an ordinary module: import faststeps. A Rust function can take Python values as typed arguments (integers, strings, lists) and return Rust values that PyO3 converts to Python objects. A Rust Err becomes a Python exception.

The example moves the loop from the benchmark thread (the longest Collatz chain below a limit) into Rust, and adds a function that parses key=value pairs to show errors.

Cargo.tomltoml
[package]
name = "faststeps"
version = "0.1.0"
edition = "2021"

[lib]
name = "faststeps"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "=0.24.2", features = ["extension-module"] }
src/lib.rsrust
use pyo3::prelude::*;

fn steps(mut n: u64) -> u32 {
    let mut s = 0;
    while n != 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        s += 1;
    }
    s
}

/// Returns (n, steps) for the longest Collatz chain below `limit`.
#[pyfunction]
fn longest_chain(py: Python<'_>, limit: u64) -> (u64, u32) {
    // the GIL is released while Rust works, so other Python threads can run
    py.allow_threads(|| {
        let mut best = (0, 0);
        for n in 1..limit {
            let s = steps(n);
            if s > best.1 {
                best = (n, s);
            }
        }
        best
    })
}

/// Parses "k=v;k=v" and raises ValueError for a malformed pair.
#[pyfunction]
fn parse_pairs(text: &str) -> PyResult<Vec<(String, i64)>> {
    text.split(';')
        .filter(|p| !p.is_empty())
        .map(|p| {
            let (k, v) = p.split_once('=').ok_or_else(|| pyo3::exceptions::PyValueError::new_err(format!("missing '=' in {p:?}")))?;
            let n = v.trim().parse::<i64>().map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{k}: {e}")))?;
            Ok((k.trim().to_string(), n))
        })
        .collect()
}

#[pymodule]
fn faststeps(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(longest_chain, m)?)?;
    m.add_function(wrap_pyfunction!(parse_pairs, m)?)?;
    Ok(())
}

To build and use it without extra tools: run cargo build --release, copy target/release/faststeps.dll to a folder as faststeps.pyd (on Linux and macOS: libfaststeps.so copied as faststeps.so), and put that folder on PYTHONPATH. That is what was done here. The usual way is maturin develop (installs into the active virtual environment) and maturin build --release (makes a wheel); maturin was not run for this thread.

The Python side times the pure-Python loop against the Rust function and checks the results:

use_it.pypython
import time, faststeps

def steps(n):
    s = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        s += 1
    return s

def py_longest(limit):
    best = (0, 0)
    for n in range(1, limit):
        s = steps(n)
        if s > best[1]:
            best = (n, s)
    return best

LIMIT = 300_000
t = time.perf_counter(); a = py_longest(LIMIT); tp = time.perf_counter() - t
t = time.perf_counter(); b = faststeps.longest_chain(LIMIT); tr = time.perf_counter() - t
print("python:", a, f"{tp*1000:.0f} ms")
print("rust  :", b, f"{tr*1000:.0f} ms")
print("same result:", a == b)
print(faststeps.parse_pairs("a=1; b = 22"))
try:
    faststeps.parse_pairs("a=1;b")
except ValueError as e:
    print("ValueError:", e)
try:
    faststeps.parse_pairs("a=x")
except ValueError as e:
    print("ValueError:", e)
text
python: (230631, 442) 4465 ms
rust  : (230631, 442) 39 ms
same result: True
[('a', 1), ('b', 22)]
ValueError: missing '=' in "b"
ValueError: a: invalid digit found in string

Three runs on one laptop gave Python times of 8125, 4465 and 4088 ms and Rust times of 76, 39 and 33 ms. The machine was shared with other work, so the spread is large; what the three runs agree on is the order of magnitude: about two orders. This is an integer loop, which is the case where an interpreter loses most. A function that spends its time inside numpy or a database driver will gain much less (see the benchmark thread).

How to do it#

  1. Profile the Python program and pick the one function that dominates. Do not port the glue.
  2. Give the Rust function the narrowest types that work: numbers, strings, Vec<T>. Converting a large Python list to a Vec copies it, so for large data pass bytes or an array buffer instead, or do more work per call.
  3. Release the interpreter lock with py.allow_threads for long computations, as above, so other Python threads keep running. Inside that closure you cannot touch Python objects.
  4. Return errors as PyResult with the exception class that Python callers expect.
  5. Test the Rust function with the same inputs as the Python one (see the thread on golden files). Keep the Python version as the reference while you check.

Common mistakes#

  • Calling the Rust function in a tight loop with tiny work per call. The conversion at each call can cost more than it saves; batch the work.
  • Building in debug mode and timing it. Use --release.
  • Forgetting that the module name in #[pymodule], the library name in Cargo.toml and the file name must agree, or the import fails.

Do I need to ship Rust to the people who use my Python package?#

No. You ship a wheel built with maturin, which contains the compiled library; users install it with pip. You need a build per platform and Python version, or the abi3 option, which PyO3 supports for one build per platform.

Can I call back into Python from Rust?#

Yes, with the Python token and Bound objects, at the cost of holding the interpreter lock while you do.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet