If you’ve ever wondered how fast Rust is compared to Python, this article is for you. I decided to create two projects performing exactly the same task to measure the performance difference between these languages. Below, I share the experiment details and the results obtained.
The Problem
For this test, I implemented a program to find all prime numbers between 1 and 10 million. This computationally intensive problem is a good benchmark for showcasing performance differences in mathematical operations and memory management.
Technologies Used
-
Python: A simple implementation using lists.
- Version: Python 3.11
- Libraries:
time
(for measurement)
-
Rust: An equivalent implementation with an optimized approach.
- Version: Rust 1.82
- Tools:
cargo
Python Code
python
Copy code
import time
def find_primes(limit):
primes = []
for num in range(2, limit + 1):
is_prime = all(num % i != 0 for i in range(2, int(num**0.5) + 1))
if is_prime:
primes.append(num)
return primes
start_time = time.time()
primes = find_primes(10_000_000)
end_time = time.time()
print(f"Found {len(primes)} primes in {end_time - start_time:.2f} seconds.")
Rust Code
rust
Copy code
use std::time::Instant;
fn find_primes(limit: u64) -> Vec<u64> {
let mut primes = Vec::new();
for num in 2..=limit {
let is_prime = (2..=((num as f64).sqrt() as u64)).all(|i| num % i != 0);
if is_prime {
primes.push(num);
}
}
primes
}
fn main() {
let start = Instant::now();
let primes = find_primes(10_000_000);
let duration = start.elapsed();
println!(
"Found {} primes in {:.2?} seconds.",
primes.len(),
duration
);
}
Tools for Measuring Performance
-
Python:
- The
time
module is used for execution time measurement. - Advanced alternative:
timeit
for more precise evaluation.
- The
-
Rust:
- The
std::time
module measures execution time directly within the program.
- The
Results
On my machine (Intel® Core™ i7-7700 CPU @ 3.60GHz × 8, 32 GB RAM):
- Python: 98.66 seconds
- Rust: 4.51 seconds
Rust was approximately 22 times faster than Python! This performance is due to its optimized machine code compilation and efficient memory handling.
Rust
Python
Conclusion
While Python excels in rapid development and prototyping, I frequently use Python, TypeScript, and Java more often than Rust. However, I’m convinced that Rust is the ideal choice for critical systems where speed and control are essential.
This experiment clarified why high-performance companies are adopting Rust. It’s undoubtedly a fascinating option for the future, especially in a world where resources are becoming scarce—whether in energy consumption (blockchain) or processing power (artificial intelligence).
What do you think? Is speed enough reason to switch to Rust in certain cases? 🧐
You can find the complete code and replicate the results here: GitHub Repository
Top comments (0)