Hello everybody! Welcome to my first article on dev.to. I'm excited to explore a powerful combination: what happens when we use Rust and Python together?
We all love Python. We love its simple syntax, its vast ecosystem of libraries (from data science to web development), and how quickly we can get ideas from our brains into code.
But...
Let's be honest. When you hit a real performance bottleneck—a complex calculation, a massive loop, or any heavy CPU-bound task—that love can turn to frustration. We've all seen our Python code crawl, often hindered by the Global Interpreter Lock (GIL) or its interpreted nature.
This is where Rust comes in.
Rust is a modern systems language built for performance. It offers C++ levels of speed but with compile-time memory safety guarantees. This means no garbage collector, no null-pointer headaches, and just... blazing speed.
So, what's the big idea?
We get the best of both worlds:
Python for the high-level logic, APIs, and its easy-to-use ecosystem.
Rust for the critical, performance-sensitive parts that need to be fast.
In this article, I'm not just going to tell you this is possible. I'm going to show you, step-by-step, how to:
- Find a "slow" function in Python.
- Rewrite its logic in Rust.
- Seamlessly plug that supercharged Rust code back into Python.
- ...and watch the performance go through the roof.
Ready? Let's get started.
The Tools We'll Need
How do we get these two languages to talk to each other? It's surprisingly simple thanks to two key tools:
PyO3: This is the magic glue. It's a set of Rust bindings for Python, allowing us to write Rust functions that can be called from Python as if they were native Python functions.
Maturin: This is our build tool. Maturin builds our Rust code into a proper Python wheel (.whl) that pip can easily install right into our virtual environment.
Let's see them in action.
Step 1: Identifying Our Bottleneck (The "Slow" Python)
First, we need a "victim." Let's create a function that is intentionally slow and CPU-bound. The classic example is a recursive Fibonacci calculator. It's a terrible way to calculate Fibonacci, which makes it a perfect demo for a performance bottleneck.
Let's create a file named test_py.py:
import time
def fib_py(n: int) -> int:
if n <= 1:
return n
return fib_py(n - 1) + fib_py(n - 2)
if __name__ == "__main__":
print("Starting the slow Python calculation...")
start_time = time.time()
result = fib_py(38) # A high enough number to feel the pain
end_time = time.time()
print(f"Result: {result}")
print(f"Time taken (Pure Python): {end_time - start_time:.4f} seconds")
here is the result:
My system :
i3 8100Y
Ram 8g ddr4
Ssd

as you can see it's a huge time spend for calculating the Fibonacci , so for fixing this problem we use Rust to help the performance of python
Step 2: Setting Up Our Rust Project
Now, let's create a new Rust library project.
if you don't have any information about rust and Cargo go to this link and learn the begin of Package of Rust : cargo
$ cargo new my_rust_module --lib
This creates a my_rust_module folder. Now, we need to tell Rust that we intend to build a Python module. Open the Cargo.toml file inside the new folder and add the following:
[package]
name = "my_rust_module"
version = "0.1.0"
edition = "2021"
# This section is NEW
[lib]
name = "my_rust_module"
crate-type = ["cdylib"]
# This section is also NEW
[dependencies]
pyo3 = { version = "0.23.3", features = ["extension-module"] }
We've done two things:
- Told Cargo to build a cdylib (a dynamic library Python can read).
- Added PyO3 as a dependency.
Step 3: Writing the "Fast" Rust Version
Now we Open src/lib.rs and Writing this:
use pyo3::prelude::*;
// This is the same, slow, recursive algorithm
// But this time, it's in Rust.
fn fib_rs_logic(n: u64) -> u64 {
if n <= 1 {
return n;
}
fib_rs_logic(n - 1) + fib_rs_logic(n - 2)
}
// This #[pyfunction] macro exposes our Rust function to Python
#[pyfunction]
fn fib_rs(n: u64) -> PyResult<u64> {
let result = fib_rs_logic(n);
Ok(result)
}
// This #[pymodule] macro creates the Python module.
// The name "my_rust_module" MUST match the `name` in Cargo.toml's [lib] section.
#[pymodule]
fn my_rust_module(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(fib_rs, m)?)?;
Ok(())
}
We use Maturin for python.
First, let's set up a Python virtual environment in the same directory as our Cargo.toml.
# Create a virtual environment
$ python3 -m venv venv
# Activate it
$ source venv/bin/activate
# Install maturin
(venv) $ pip install maturin
and then Run this from inside our my_rust_module directory:
(venv) $ maturin develop
Maturin will compile out Rust code (which might take a moment the first time) and install the resulting module directly into oyr active virtual environment. It's now available to Python just like any other pip package.
Time to test it:)) Create a new file, test_rs.py:
import time
from my_rust_module import fib_rs # Look! We're importing our Rust code!
if __name__ == "__main__":
print("Starting the 'fast' Rust-in-Python calculation...")
start_time = time.time()
# We're calling the Rust function here
result = fib_rs(38)
end_time = time.time()
print(f"Result: {result}")
print(f"Time taken (Python + Rust): {end_time - start_time:.4f} seconds")
here is the result:
The Moment of Truth: Benchmarks
We built the module, installed it, and ran the tests. Here is the comparison on my local machine:
| Method | Time Taken | Speedup |
|---|---|---|
| Pure Python | 18.48s | 1x |
| Python + Rust | 0.46s | ~40x 🚀 |
What just happened?
We didn't optimize the Fibonacci algorithm itself (it's still the inefficient recursive version). We simply moved the logic to Rust.
By doing this, we reduced the execution time from over 18 seconds to under half a second. That is a 4000% performance increase just by using PyO3.
Conclusion
As we've seen, you don't need to rewrite your entire codebase in Rust to get its benefits. Python is fantastic for 99% of your application, but for that 1% that is CPU-intensive, Rust is the perfect sidekick.
With tools like PyO3 and Maturin, the barrier to entry is lower than ever.
Thanks for reading my first post!
What's a bottleneck in your project you'd like to crush with Rust? Let me know in the comments!
And if you have any problem or question comment it I will answer

Top comments (0)