Accelerating Python Performance with Rust

Rust offers significant performance advantages over Python, a dynamically-typed interpreted language. While Python excels in rapid development and flexibility, its execution speed can be a bottleneck for computationally intensive tasks. This article explores the performance disparity between Python and Rust and demonstrates how to leverage Rust to enhance Python program execution speed.

1. Performance Comparison: Python vs. Rust

To illustrate the performance difference, let's compare the execution time of calculating the 30th Fibonacci number iterated 50 times in both languages. #### 1.1 Python Implementation:

import time

def calculate_fibonacci(n):
    if n <= 1:
        return n
    return calculate_fibonacci(n - 1) + calculate_fibonacci(n - 2)

def main_python(iterations=50):
    start_time = time.time()
    for _ in range(iterations):
        calculate_fibonacci(30)
    end_time = time.time()
    print(f"Python Total time: {end_time - start_time:.6f} seconds")

main_python()
# Expected Output: Python Total time: 7.306154 seconds

The Python version takes over 7 seconds, which is often unacceptable for performance-critical applications. #### 1.2 Rust Implementation:

Rust's official documentation touts its remarkable speed. Here's the equivalent Fibonacci calculation in Rust: ``` use std::time;

fn fibonacci(n: i32) -> u64 { match n { 1 | 2 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } }

fn main() { let num_iterations = 50; let start_instant = time::Instant::now(); for _ in 0..num_iterations { fibonacci(30); } let elapsed_duration = start_instant.elapsed(); println!("Rust Total time: {:?}", elapsed_duration); } // Expected Output: Rust Total time: 179.774166ms


The Rust implementation completes in approximately 179.77 milliseconds, making it nearly 40 times faster than the Python version. While Rust offers superior performance, its syntax can be less intuitive and present a steeper learning curve for Python developers. A compelling solution involves using Python as the primary language for development and integrating Rust components for performance-critical sections. ### 2. Rewriting Slow Python Functions with Rust

The Python community has actively developed tools to facilitate this integration. One prominent method is using PyO3, a library that enables seamless integration between Rust and the Python interpreter. First, install the `maturin` build tool: ```
pip install maturin

Next, initialize the necessary Rust project structure: ``` maturin init


During initialization, you'll have options for how to set up the Rust bindings. Select PyO3. This command generates the required project files. The key files to modify are `Cargo.toml` and `lib.rs`. `Cargo.toml` serves as the package manifest, written in TOML format, and contains metadata essential for building the package. In this example, rename the package to `rustFib` and retain other default settings: ```
[package]
name = "rustFib"
version = "0.1.0"
edition = "2021"

[lib]
name = "rustFib"
crate-type = ["cdylib"] # Compile as a dynamic library for Python

[dependencies]
pyo3 = "0.19.0"

The lib.rs file is where the Rust code that will replace slow Python functions resides: ``` use pyo3::prelude::*;

/// Fibonacci function implemented in Rust. #[pyfunction] fn calculate_fibonacci_rust(n: i32) -> u64 { match n { 1 | 2 => 1, _ => calculate_fibonacci_rust(n - 1) + calculate_fibonacci_rust(n - 2), } }

/// Python module definition. #[pymodule] fn rustFib(_py: Python, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(calculate_fibonacci_rust, m)?)?; Ok(()) }


Finally, compile the Rust code into a Python-installable package: ```
maturin develop

This command builds the rustFib Python package using Rust. The performance should now rival the standalone Rust program. Test the integrated module in Python: ``` import time from rustFib import calculate_fibonacci_rust

def main_integrated(iterations=50): start_time = time.time() for _ in range(iterations): calculate_fibonacci_rust(30) end_time = time.time() print(f"Integrated Total time: {end_time - start_time:.6f} seconds")

main_integrated()

Expected Output: Integrated Total time: 0.176841 seconds


The execution time drops significantly to approximately 0.176 milliseconds, demonstrating the dramatic performance boost achieved by integrating Rust in to Python. 

Tags: python rust Performance PyO3 Maturin

Posted on Sun, 16 Aug 2026 16:09:07 +0000 by jdock1