← All posts

Moving a Python Pipeline's Hot Loop into Rust with PyO3

Python is quick to write and slow in a tight loop. When a pipeline spends most of its time in one such loop, there are three ways out: express it in numpy, move it into a compiled language, or batch and leave it. This post is about the second: moving one loop into Rust with PyO3. It covers when that pays and when it does not, what each call into Rust costs, how to pass numpy arrays without copying, how to release the GIL and use threads, how to ship the result as a wheel, and one trap that installed my module in the wrong environment.

On 4,000 rows of 1,000 bytes, a branchy scoring kernel took a median of 177 ms in pure Python, 23.5 ms in numpy, 4.44 ms in Rust on one thread and 0.73 ms in Rust on eight threads with the GIL released. That is the case where moving a loop into Rust pays. Two other cases paid little or nothing. A kernel numpy already vectorises ran only 1.4 times faster in Rust, on a 100,000-row array. A call that carries a handful of elements gained nothing, because each call into Rust has a fixed cost. A second stateful kernel confirmed the first case: 4.5 times faster than numpy.

I prefer Rust for compute-bound code, and I prototyped a Rust-based observability platform at an AI infrastructure company in 2025. Two of my own projects call Rust crates from Python, and one maturin trap once sent my module to the wrong environment. In one of them, a Rust pileup made a whole genotyping run 3.9 times faster. Apart from that run, the numbers below come from a small lab you can run, built with PyO3 0.30.1, rust-numpy 0.30.0 and maturin 1.16.0.

In short

  • Rust pays for CPU-bound loops numpy cannot vectorise: state carried between elements, a branch per element, parsing. In the lab it was 5.3 times faster than numpy on one thread, and a second kernel showed 4.5 times.
  • On a real stage, a BAM genotyper in my genomics project, Rust ran the pileup 12.3 times faster and the whole single-sample run 3.9 times faster, as Amdahl's law predicts.
  • It pays little where numpy already runs compiled code (1.4 times in the lab), and not at all for I/O waits.
  • A call into Rust has a fixed cost of about 230 ns in the lab. Cross the boundary once per batch.
  • Read numpy arrays in place, release the GIL with Python::detach (allow_threads before PyO3 0.26) and use rayon. Two threads overlapped fully with the GIL released and took twice as long with it held.
  • Build with maturin and abi3, and install by naming the interpreter. maturin develop installs into whatever VIRTUAL_ENV the shell exports.

When Rust pays

A flow chart of three yes or no questions. Is the time spent in Python code? If not, fix the I/O. Can numpy express the work as whole-array operations? If so, use numpy. Does one call carry enough work? If not, batch the calls first. If all three are answered as shown, move the loop into Rust and keep the batch as the boundary Does a hot loop belong in Rust? Three questions, in order 1. Is the time spent in Python code? not waiting on disk, network or a database 2. Can numpy express it as whole-array operations, with no step that needs the last? 3. Does one call carry enough work? hundreds of elements or more, not one Move the loop into Rust and keep the batch as the boundary yes yes yes No: fix the I/O. A faster language does not shorten a wait. Yes: use numpy. In the lab a counting kernel was only 1.4 times faster in Rust. No: batch the calls first, or stay in Python. At 8 elements per call the lab saw no gain. Then measure on your own data before you keep it.
Figure 1. Three questions before moving a loop. The side notes are from the lab.

Profile first. A faster language does not shorten a wait on a disk, a network or a database. If the time goes to a Python loop, ask whether numpy can express it. A per-row count of values at or above a threshold can. On 100,000 rows of 1,000 bytes it took 19.6 ms in numpy and 14.1 ms in single-threaded Rust.

Loops with state cannot be written that way. The lab kernel keeps a run length per row. A byte at or above the threshold extends the run, and once the run reaches a minimum length it adds the run length to the score. A zero byte ends the run and costs 3 points if one was open. Any other byte halves the run. Each step needs the state left by the last one, so the lab's numpy version loops over the 1,000 columns in Python and handles all rows at once in each step. It took 5.3 times as long as the Rust loop.

ImplementationMedian (ms)IQR (ms)RunsSpeed vs numpy
Pure Python177176 to 178210.13
numpy, loop over columns23.523.4 to 23.6211.00
Rust, 1 thread4.444.44 to 4.45215.29
Rust, 1 thread, GIL held4.464.44 to 4.53215.27
Rust + rayon, 2 threads2.272.26 to 2.272110.36
Rust + rayon, 4 threads1.221.20 to 1.242119.30
Rust + rayon, 8 threads0.730.71 to 0.762132.12
Horizontal bars on a logarithmic time axis for six implementations of one kernel on 4,000 rows of 1,000 bytes. Pure Python 177 ms, numpy 23.5 ms, Rust one thread 4.44 ms, Rust with rayon on 2, 4 and 8 threads 2.27, 1.22 and 0.73 ms. Whiskers show the interquartile range over 21 runs and are narrow Median time, 4,000 rows of 1,000 bytes; whiskers: interquartile range vs numpy pure Python 177 ms 0.13x numpy 23.5 ms 1.00x Rust, 1 thread 4.44 ms 5.29x Rust + rayon, 2 threads 2.27 ms 10x Rust + rayon, 4 threads 1.22 ms 19x Rust + rayon, 8 threads 0.73 ms 32x 1 ms 10 ms 100 ms Log axis. The machine was shared with another workload, so the timings are indicative.
Figure 2. Median time for the same kernel, with interquartile-range whiskers over 21 runs.

Pure Python took 40 times as long as Rust on one thread. A pipeline that already uses numpy should compare against the 5.3, not the 40.

To check that the pattern is not one function, the lab has a second kernel with carried state: a row switches on at a byte of 200 or more and off at 100 or less, and the kernel counts the switch-ons. It ran on the same 4,000 rows.

ImplementationMedian (ms)IQR (ms)RunsSpeed vs numpy
Pure Python124123 to 125210.09
numpy, loop over columns11.211.2 to 11.3211.00
Rust, 1 thread2.522.50 to 2.53214.46
Rust + rayon, 8 threads0.480.46 to 0.502123.44

What the loop is worth to the whole pipeline

A faster loop speeds up the pipeline only as far as the loop's share of the run time. Amdahl's law gives the limit. If the loop takes a fraction p of the run time and becomes s times faster, the whole run speeds up by

speed-up = 1 / ((1 − p) + p / s)

The values of s below are from the lab: 5.29 for one Rust thread against numpy, and 32.1 for eight threads against numpy. The shares p are illustrative. They are not measurements of any pipeline.

Loop becomes faster byp = 0.50p = 0.80p = 0.95
1 Rust thread vs numpy (s = 5.29)1.68x2.85x4.36x
8 Rust threads vs numpy (s = 32.12)1.94x4.45x12.57x

A loop that is half the run time cannot give more than a factor of 2, whatever the language. Measure p before you start.

A real stage: genotyping in my genomics project

The shares above are made up. Here is a measured one. My genomics project decides, for each sample, which allele its reads show at about 20,000 known sites on the Y chromosome. That pileup is the one place where the project replaced Python with Rust. The rest of its critical path runs samtools, bcftools and bwa, which are already compiled C, so a port would gain nothing there. When the kernel was written in August 2026, a profile put the Python pileup at 0.973 s of a 1.02 s run.

I re-timed it on 5 December 2026, on the one real chrY slice on this machine that the genotyper accepts: 10 MB, aligned to GRCh37, against a panel of 20,230 sites. Each engine ran its full production path, including the evidence file it writes beside the calls. The figures are medians of 5 Python and 9 Rust runs, taken at low priority beside another pipeline, and they leave out interpreter start-up.

StepPythonRust
Import the genotyper module0.047 s0.047 s
Load the 20,230-site panel0.140 s0.140* s
Genotype the slice, with its evidence file0.795 s0.065 s
One sample, start to finish0.98 s0.25 s

* plus 0.002 s to copy the panel into Rust.

Two horizontal stacked bars on one time axis. The Python run: a short plain segment for import and panel load, 0.19 s, then a long accent segment for the pileup, 0.795 s, total 0.98 s. The Rust run: the same plain segment, then a short accent segment for the pileup, 0.065 s, total 0.25 s One genotyping run on a real 10 MB chrY slice: where the time goes Python pileup 0.795 s, 81% of the run total 0.98 s Rust pileup 0.065 s; total 0.25 s plain bars: import and panel load, 0.19 s, the same for both 0 0.25 s 0.50 s 0.75 s Pileup 12.3 times faster; whole run 3.9 times. Amdahl's law with p = 0.81 and s = 12.3 gives 3.9. Medians of 5 Python and 9 Rust runs, interpreter start-up excluded. Identical calls and evidence bytes from both.
Figure 3. One genotyping run on a real slice. Rust removes most of the pileup time; the import and the panel load stay.

The pileup ran 12.3 times faster in Rust, and 12.2 times in a second, separate run. Both engines returned identical calls and byte-identical evidence files. The pileup was 81% of today's single-sample run, against 95% in the August profile. With that share, Amdahl's law predicts 1 / (0.19 + 0.81 / 12.3) = 3.9 times for the whole run, and the clock gave 0.98 s against 0.25 s, also 3.9 times. A batch loads the panel once, so each further sample gains close to the full 12 times.

Two more lessons from that port. Part of the gain came from the algorithm in the loop, not the language: replacing a hash lookup per aligned base with one bit test took the kernel from 5 to 9.7 times faster at the time. And the parity tests found a bug in the reference. The Python consensus broke ties in set iteration order, which changes with hash randomisation, so the same file gave between 3,007 and 3,010 derived calls from one run to the next. Both engines now refuse to call a tie.

The other three BAM files on the machine are aligned to GRCh38, which the genotyper refuses at once. That check took 1.3 ms in Python and 2.1 ms in Rust: when a call does almost no work, the fixed cost of crossing into Rust decides, as the next section shows. This measurement is not in the lab, because that code is closed.

What a call into Rust costs

Each call builds arguments, checks them, runs the function and converts the result. That cost does not depend on how much work the function does. In the lab:

  • An empty Python function call took 31.8 ns. An empty Rust function through PyO3 took 44.7 ns.
  • Scoring 8 bytes took 328 ns in Python and 66.3 ns in Rust when the bytes were passed as a bytes object.
  • A Rust call on a one-row numpy array of 64 bytes took 289 ns. At 8 elements per call, Python (328 ns) and Rust on an array (289 ns) were about even.

Time per row falls as the batch grows. It was 299 ns at one row, 99 ns at 8 rows, and about 70 ns from 128 rows on. A Python loop that called Rust once per 64-byte row cost 285 ns per row. The pure Python loop cost 2,492 ns per row, so per-row calls were 8.8 times faster and batched calls about 36 times faster.

A log-log chart of time per row against rows per call. A blue line falls from 299 ns per row at one row to 99 ns at 8 rows and settles near 70 ns from 128 rows upward. Two dashed horizontal lines mark pure Python at about 2,500 ns per row and Rust called once per row at about 285 ns Time per row as the batch grows (rows of 64 bytes; log scales) 40 ns 100 ns 1 µs 4 µs 1 4 16 64 256 1024 4096 rows per call to Rust pure Python: 2,492 ns per row Rust, one call per row: 285 ns Rust, one call per batch settles at about 69 ns per row 299 ns at one row
Figure 4. The fixed cost per call is spread over the batch. Medians of 21 runs per point.

Several numbers above describe a call with one row, and they agree within about 5%: 289 ns (a loop of 50,000 calls), 285 ns (a loop over 512 pre-cut one-row slices), 299 ns (the one-row point on the batch curve) and 300 ns from the model below. A simple model fits the whole curve. With n rows per call:

t(n) = c + n r

A least-squares fit to the 13 batch sizes, weighted by relative error, gave c = 230.5 ns per call and r = 69.3 ns per row. Every point is within 1.3% of the line. So c is the call with no rows, and a one-row call is c + r. The 66.3 ns call above is cheaper because it takes bytes and returns one integer. I did not measure how much of the gap is array handling.

Pure Python cost 2,492 ns for a 64-byte row, or 38.9 ns per byte. Rust cost 69.3 / 64 = 1.08 ns per byte. Rust wins above

c / (38.9 − 1.08) ≈ 6 bytes

That is about 6 elements per call. The direct comparison above, parity near 8, agrees. Below that, batch before you cross.

Passing numpy arrays without copying

rust-numpy 0.30.0 provides "Rust interfaces for NumPy C APIs, especially for the ndarray class". Its read-only borrow is PyReadonlyArray2<'py, u8> for a two-dimensional byte array. The docs call it a "Read-only borrow of an array" and say that it rules out any PyReadwriteArray on the same array. Its as_slice method gives "an immutable slice view of the interior of the NumPy array if it is contiguous", or an AsSliceError if not. Here is the lab's single-thread entry point:

#[pyfunction]
#[pyo3(signature = (arr, threshold, min_run, release_gil=true))]
fn score_st<'py>(
    py: Python<'py>,
    arr: PyReadonlyArray2<'py, u8>,
    threshold: u8,
    min_run: i64,
    release_gil: bool,
) -> PyResult<Bound<'py, PyArray1<i64>>> {
    let (data, width) = rows(&arr, min_run)?;   // arr.as_slice() inside, or a ScoreError
    let out = if release_gil {
        py.detach(|| score_chunk(data, width, threshold, min_run))
    } else {
        score_chunk(data, width, threshold, min_run)
    };
    Ok(PyArray1::from_vec(py, out))
}

Three points.

The slice is the buffer. The test test_rust_sees_the_same_address returns the address of the first element Rust sees and compares it with numpy's arr.ctypes.data. They match, so the 4 MB array was not copied. A read-only array (flags.writeable = False) is accepted, since the borrow is a read.

Contiguity is the caller's job. A strided view such as a[:, ::2] has no single slice. The lab raises an error that says to call np.ascontiguousarray, so the copy shows up in the caller's code. as_array returns an ndarray view that handles strides, if you prefer to accept any layout.

Borrows are checked at run time. Many shared borrows may coexist, and the docs say borrow panics if the array is already mutably borrowed. Take the borrow once, at the top of the function.

The output is a new array built with PyArray1::from_vec. The Python side is short:

import numpy as np
import rustpy_lab as r

batch = np.ascontiguousarray(batch, dtype=np.uint8)   # copies only if it must
scores = r.score_par(batch, 128, 3, 8)                # whole batch, one call, 8 threads
Four boxes in a row joined by arrows. A numpy array, uint8, 2-D, owned by Python. Rust borrows it as PyReadonlyArray2 and as_slice, with no copy. The GIL is released with py.detach and rayon workers run the loop. A numpy array of int64 comes out, built from a Vec. Notes say the pointer, shape, arguments and result cross once per call, and the elements do not cross What crosses the boundary in one call, and what does not numpy array uint8, 2-D, C-contiguous owned by Python Rust borrows it PyReadonlyArray2 as_slice: &[u8], no copy GIL released py.detach(...) rayon workers run the loop numpy array out int64, one per row built from a Vec Crosses once per call: the pointer, the shape, the arguments, the result. Does not cross: the elements. Fixed cost in the lab, a call with 1 row: about 289 ns. A non-contiguous or wrong-dtype array is refused with an exception instead of being copied silently. While the GIL is released, no Python object may be touched inside the closure.
Figure 5. One call: what crosses the boundary and what stays where it is.

Releasing the GIL, and rayon

While Rust runs inside a PyO3 function, the calling thread keeps the GIL and no other Python thread runs. The PyO3 0.30.1 guide says: "The Python::detach method can be used to allow the Python interpreter to do other work while the Rust work is ongoing". The API page gives the signature as pub fn detach<T, F>(self, f: F) -> T where F: Ungil + FnOnce() -> T, T: Ungil.

Older code calls this allow_threads. The migration guide, under "from 0.25.* to 0.26", says: "Python::allow_threads is now called Python::detach". It also renames with_gil to attach. Check the PyO3 version of an example before you copy it.

The closure must be Ungil, so it cannot capture Python-bound references such as Bound<'py, ...>. The docs show a failing example that captures a PyString. A plain &[u8] borrowed from the numpy array is accepted.

In the lab, two Python threads each ran the same single-thread kernel over 60,000 rows. One thread alone took 66.2 ms (interquartile range 66.0 to 67.0 over 21 runs). Two threads with the GIL released took 67.0 ms (66.9 to 67.2). With the GIL held they took 132.4 ms (131.8 to 133.2).

A timeline of two Python threads. With the GIL held, thread 1 runs for 66.2 ms and thread 2 waits and then runs until 132.4 ms. With the GIL released, both threads run from 0 to 67.0 ms at the same time Two Python threads, each scoring 60,000 rows of 1,000 bytes GIL held thread 1 thread 2 runs waits, then runs GIL released thread 1 thread 2 runs runs at the same time 0 66.2 ms 132.4 ms Medians of 21 runs. One thread alone: 66.2 ms. Both threads finished at 132.4 ms (held) and 67.0 ms (released).
Figure 6. The same two jobs, with the GIL held and released. Medians of 21 runs.

Releasing the GIL costs nothing visible for one call: 4.44 ms released and 4.46 ms held on the 4,000-row case.

Rayon splits the work over threads. The lab kernel uses par_chunks_exact(width), one row per item, inside py.detach. The PyO3 parallelism guide says: "You should always call detach in situations that spawn worker threads".

With tk the time on k threads, the speed-up is S(k) = t1 / tk and the parallel efficiency is

E(k) = S(k) / k

Threads4,000 rows (ms)Speed-upEfficiency100,000 rows (ms)Speed-upEfficiency
14.441.00100%111.51.00100%
22.271.9698%55.72.00100%
41.223.6591%28.13.9799%
80.736.0776%14.37.8098%
A chart of speed-up against thread count, with a dashed ideal line from 1 at one thread to 8 at eight threads. For 100,000 rows the measured points are 2.00, 3.97 and 7.80 times at 2, 4 and 8 threads. For 4,000 rows they are 1.96, 3.65 and 6.07 times. Efficiency at 8 threads is 98% for the large input and 76% for the small one Speed-up of the Rust kernel against its own single thread 2x 4x 6x 8x 1 2 4 8 threads ideal 7.80x 6.07x Efficiency speed-up divided by threads 2 threads 100% (large), 98% (small) 4 threads 99% (large), 91% (small) 8 threads 98% (large), 76% (small) Tinted points: 100,000 rows. Plain points: 4,000 rows. Medians; the thread pool is rebuilt on each call.
Figure 7. Measured speed-up against the ideal line. The 4,000-row input scales less well.

The lab builds a new thread pool on every call so that it can vary the thread count. I did not measure how much of the small input's lower efficiency that explains. A service would build one pool and keep it. On the large input, eight threads were 34 times faster than numpy (489 ms against 14.3 ms).

Another pipeline shared the machine, so expect different speed-ups elsewhere. The PyO3 guide also mentions free-threaded Python, "supported since Python 3.14", as another route to parallel threads.

Errors become Python exceptions

A PyO3 function that can fail returns PyResult<T>, an alias for Result<T, PyErr>. An Err is raised in Python. PyO3 also converts a returned Result<T, E> "as long as there is an implementation of std::convert::From<E> for PyErr". A parse error, for example, arrives as ValueError. For your own failures, PyValueError::new_err("x is negative") builds the error.

The lab follows three rules, each tested in tests/test_errors.py:

  • Let the argument types do the checking. A float array where uint8 is expected, or a one-dimensional array where two dimensions are expected, raises TypeError. A threshold of 300 or −1 for a u8 raises OverflowError.
  • Give domain failures a class under a built-in one. The lab declares create_exception!(_core, ScoreError, PyValueError, "..."). It raises it for a minimum run below 1, empty rows and a non-contiguous array. Code that catches ValueError keeps working, and code that wants the detail can catch ScoreError.
  • Say what to do. "array must be C-contiguous; call np.ascontiguousarray first" helps more than "invalid array".

The binding crate of my stock-research system does the same on a larger scale. It declares one base exception that subclasses ValueError, and one subclass for each reason a plan is refused. The caller can tell a stale input from an out-of-range one by class. The rust-numpy docs warn that "the functions provided by this crate will panic instead of returning a result" in some cases. Keep array handling at the top of a binding function.

Packaging with maturin

A pyproject.toml names maturin as the build backend. The maturin tutorial's minimal form is requires = ["maturin>=1.0,<2.0"] with build-backend = "maturin". The lab keeps Python code in python/rustpy_lab/ and the compiled module as rustpy_lab._core.

[build-system]
requires = ["maturin>=1.9.4,<2.0"]
build-backend = "maturin"

[tool.maturin]
python-source = "python"
module-name = "rustpy_lab._core"
[lib]
name = "_core"
crate-type = ["cdylib"]

[dependencies]
pyo3 = { version = "0.30.1", features = ["abi3-py39"] }
numpy = "0.30.0"
rayon = "1.12"

[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 1
On the left, a repository with pyproject.toml, Cargo.toml, src/lib.rs, a python package folder with __init__.py and pure.py, and tests. An arrow labelled maturin build leads to a wheel named rustpy_lab 0.1.0 cp39 abi3 macosx 11 0 arm64 containing the Python files and one compiled _core.abi3.so file. Below it, a CI box builds one wheel per operating system and architecture One repository, one build step, one wheel per platform pyproject.toml build-backend = maturin Cargo.toml pyo3 (abi3-py39), numpy, rayon src/lib.rs the Rust kernel and #[pymodule] python/rustpy_lab/__init__.py re-exports, pure fallbacks python/rustpy_lab/pure.py reference implementations tests/ pytest: both sides through Python the wheel rustpy_lab-0.1.0-cp39-abi3- macosx_11_0_arm64.whl rustpy_lab/__init__.py rustpy_lab/pure.py rustpy_lab/_core.abi3.so dist-info (metadata) maturin build CI: one job per OS and architecture each uploads its wheel abi3: the same compiled file loads on CPython 3.9 and later, so the matrix is platforms, not Python versions.
Figure 8. From repository to wheel. The wheel name is the one maturin produced in the lab.

abi3. The PyO3 guide lists "feature flags abi3-py39, abi3-py310, abi3-py311 etc." and says that with several set, "the lowest version always wins". maturin built rustpy_lab-0.1.0-cp39-abi3-macosx_11_0_arm64.whl and printed "Built wheel for abi3 Python ≥ 3.9". The tag means one compiled file for CPython 3.9 and later on that platform, so the matrix is platforms only, not platforms times Python versions. rust-numpy 0.30.0 built under the feature without changes. Its README does not mention abi3, so that is what I saw, not a promise. I loaded the wheel on Python 3.13 only. A free-threaded build "has its own stable ABI, abi3t" (maturin-action README), so it needs a separate wheel.

The extension-module feature. Older tutorials enable pyo3/extension-module, which the current guide calls historical. It "caused linking to be disabled for all compile targets, including Rust tests and benchmarks". It adds that "maturin >= 1.9.4 and setuptools-rust >= 1.12 will set this for you automatically" through PYO3_BUILD_EXTENSION_MODULE. The lab's build log shows maturin setting it. Of my two projects' binding crates, one still lists the feature and one does not.

One wheel per platform. A compiled wheel fits one operating system and one CPU architecture. The maturin guide says that "native python modules on linux must only dynamically link a set of libraries and symbols called manylinux and musllinux". To publish Linux wheels you "need to use a manylinux docker image or build with zig". maturin generate-ci github writes the matrix, using PyO3/maturin-action, which runs "a custom maturin command with built-in support for cross compilation". Figure 9 shows what maturin 1.16.0 wrote for the lab. I read the file and did not run it.

Five build jobs feed one release job. Linux manylinux builds x86_64, x86, aarch64, armv7, s390x and ppc64le. Musllinux builds x86_64, x86, aarch64 and armv7. Windows builds x64, x86 and aarch64. macOS builds x86_64 and aarch64. A source distribution job also runs. All produce abi3 wheels or the sdist, and the release job needs all five What maturin generate-ci (maturin 1.16.0) wrote: platforms in, one release out linux (manylinux) x86_64, x86, aarch64, armv7, s390x, ppc64le musllinux x86_64, x86, aarch64, armv7 windows x64, x86, aarch64 macos x86_64, aarch64 sdist source distribution abi3 wheels one per target plus the sdist release job needs all five Each job builds with PyO3/maturin-action. The linux jobs use manylinux: auto. The generated file also builds free-threaded wheels with -i python3.14t, a separate build from abi3.
Figure 9. The CI matrix written by maturin generate-ci. Trim it to the platforms you ship to.

In my stock-research system the logic lives in plain Rust crates with no Python in them: domain types and pure planning logic, a store crate for file formats, and ingest and engine crates for the programs that run. The PyO3 crate on top is thin, is built by maturin and has no Rust tests. The Python test suite covers it through the module. Without PyO3 in them, the core crates run under cargo test with no interpreter. My genomics project keeps its Rust genotype code in one crate, built by maturin as its own package, with opt-level = 3, link-time optimisation and one codegen unit. That code is closed. Neither project's binding crate uses abi3 yet. The lab does.

Choosing between the options

OptionWhat it needsWhat the lab showed
Pure PythonNothing177 ms for 4,000 rows. It is the reference the other versions are tested against.
numpyA whole-array form of the loop19.6 ms for the counting kernel on 100,000 rows. 23.5 ms for the stateful kernel on 4,000 rows, using a Python loop over columns.
Rust through PyO3A Rust toolchain, maturin, a wheel per platform4.44 ms on one thread and 0.73 ms on eight for the same 4,000 rows. A fixed cost of about 230 ns per call.

Testing both sides

Every implementation must return the same integers. Integer scores need no tolerance, and an exact comparison catches an off-by-one in a branch that a tolerance would hide. The pure Python version is the reference, and it stays in the package as the plain statement of what the kernel means.

@pytest.mark.parametrize("threshold,min_run", [(128, 3), (1, 1), (200, 5), (255, 1)])
def test_all_implementations_agree(rng, threshold, min_run):
    a = rng.integers(0, 256, (500, 97), dtype=np.uint8)
    a[rng.random(a.shape) < 0.15] = 0        # make every branch run
    a[rng.random(a.shape) < 0.30] = 255
    ref = r.score_python_rows(a, threshold, min_run)
    assert np.array_equal(r.score_numpy(a, threshold, min_run), ref)
    assert np.array_equal(r.score_st(a, threshold, min_run), ref)
    assert np.array_equal(r.score_par(a, threshold, min_run, 3), ref)

The lab has 47 tests in five groups:

  • Agreement. A hand-computed row, then random arrays in several shapes, including one row and one column, for both kernels, with extra zeros and 255s so every branch runs.
  • Error mapping. Each failure above raises the class the lab names.
  • No copy. The address test.
  • GIL overlap. The two-thread test fails if the GIL is held.
  • Environment. The install test in the next section.

Test the Rust through Python, because that is how it is used. Argument extraction, error mapping and the buffer handoff are the parts a Rust-only test never reaches.

The trap: maturin develop installs where the shell says

I ran maturin develop in one project while my shell still had VIRTUAL_ENV exported from another project's virtual environment. The build succeeded and maturin reported the install. The module went into the other environment. Nothing failed until the project I was working in could not import it.

The maturin tutorial says "maturin develop actually skips the wheel generation part and installs directly in the current environment". It does not say how the environment is found. In my tests with maturin 1.16.0 on macOS, with VIRTUAL_ENV set to a second environment, maturin printed "Found CPython 3.13 at" that environment's interpreter and installed there. The test test_develop_follows_virtual_env_and_wheel_install_does_not creates two fresh environments, exports one, and checks that develop lands in the exported one.

The shell has VIRTUAL_ENV set to another project's virtual environment. maturin develop, run from the project checkout, installs the module into that environment. The environment the developer meant gets nothing, and the import fails later. The fix is to run maturin build and then python -m pip install of the wheel using the intended interpreter Where maturin develop installs: the environment the shell exports shell has exported VIRTUAL_ENV = other venv maturin develop run in this project other project's venv module installed here the venv you meant import fails later Fix: build a wheel, install by interpreter maturin build --release -o dist <venv>/bin/python -m pip install dist/*.whl Or set VIRTUAL_ENV to the venv you meant, in the same command, before maturin develop.
Figure 10. Where the module lands is decided by the environment variable, not by the checkout you are in.

Two fixes. Set VIRTUAL_ENV in the command: VIRTUAL_ENV=$PWD/.venv maturin develop --release. Or skip develop: run maturin build --release -o dist, then .venv/bin/python -m pip install dist/*.whl. The second names the interpreter, so nothing is guessed, and it installs the wheel you would ship. The same test checks it.

A small lab you can run

The lab is a crate and a Python package. It builds with maturin in a virtual environment inside its own folder.

python3 -m venv .venv && . .venv/bin/activate
pip install maturin numpy pytest
export CARGO_TARGET_DIR=$PWD/target CARGO_BUILD_JOBS=2 VIRTUAL_ENV=$PWD/.venv
nice maturin develop --release
python -m pytest -q
nice python bench.py

Versions: Rust 1.97.1, PyO3 0.30.1, rust-numpy 0.30.0, rayon 1.12, maturin 1.16.0, Python 3.13.7, numpy 2.5.5, on an arm64 Mac with 16 logical cores. Every main timing is the median of 21 runs, with the interquartile range. Another pipeline ran on the machine throughout, so the timings are indicative, and the ratios are firmer than the absolute figures.

Two separate runs

I ran the whole benchmark twice, in separate processes, and compared the medians. The 1-minute load average is the machine load when each run started.

Median (ms)Run ARun BB against A
Kernel 1, pure Python177170-3.7%
Kernel 1, numpy23.523.0-1.9%
Kernel 1, Rust 1 thread4.444.40-0.9%
Kernel 1, Rust 8 threads0.730.71-3.6%
Kernel 1 large, numpy489456-6.7%
Kernel 1 large, Rust 1 thread112109-2.1%
Kernel 1 large, Rust 8 threads14.314.2-0.4%
Kernel 2, numpy11.210.9-2.9%
Kernel 2, Rust 1 thread2.522.45-2.8%
Counting kernel, numpy19.618.8-3.9%
Counting kernel, Rust 1 thread14.113.7-2.5%
Load average (1 min) at start2.94.2

The ratios held from one run to the other. The largest change was the numpy run on the large input, which also has the widest spread within a run.

Checklist before you move a loop

  1. Profile. Confirm the time is in a Python loop and not in I/O.
  2. Keep the pure Python version as the reference, and test every other version against it for exact equality.
  3. Try numpy first. If a whole-array form exists, measure it. In the lab the gain from Rust there was 1.4 times.
  4. Count the elements per call. The lab's fixed cost was about 230 ns, and break-even was about 6 elements. Batch before you cross.
  5. Pass contiguous arrays and test that Rust sees the same address. Refuse strided input with a clear error.
  6. Release the GIL around the loop with py.detach, and test that two threads overlap.
  7. Raise a subclass of a built-in exception, test the type, and install by naming the interpreter so VIRTUAL_ENV cannot decide for you.

Limits of this post

  • Three small kernels on one machine. Ratios depend on the kernel, the row length, the CPU and the load.
  • The numpy version is the best form I found for a kernel that loops over columns. I did not try numba or Cython.
  • The rayon pool is rebuilt on every call, which may understate the gain on small inputs.
  • The cost model uses 13 points from one machine. The Amdahl table's shares are illustrative. The genotyper's share is measured on one 10 MB file, and real files differ widely in coverage. I did not build wheels for other platforms or load the wheel on other Python versions. I did not measure an I/O-bound case.
  • The trap was seen with maturin 1.16.0 on macOS only. Panics, async calls and memory use are not covered.

Sources