Rust is not a new language, but lately it has gotten way more popular, especially as a tool to speed up Python. What gets me excited here is this idea: I want to try having Python call a Rust library just to see the difference in speed and safety. Python is easy to write and great to use, but it can be slow, while Rust is really fast and takes care of things like memory safety.
This week, I read an article about how Rust usage for Python extensions jumped about 22 percent in a year, up from 27 to 33 percent, which shows developers want that combo of C-like speed and safety. Libraries like PyTorch use C and talk to the GPU, but Rust is gaining ground because it helps prevent bugs and memory leaks with a strict compiler, even though modern C compilers are also improving. Now, a lot of Python's big libraries use C, like NumPy, and machine learning tools like PyTorch use C bindings, but today I want to use Rust because it gives you more safety.
So here's the plan: I’ll make a Rust library, call it from Python, and then see how fast basic multiplication runs in both. The process is pretty simple. I create a Rust project using `maturin` and `pyo3` for bindings, install Rust, check my Python version, then build it all.
After I get the Rust function working as a Python module, I write a Python script to test it, and I try multiplying numbers to make sure everything works. Next, I set up a benchmark to compare native Python and Rust multiply functions by running each in a loop millions of times. What we notice is that if you call Rust for each multiplication from Python, it is actually slower because each call has overhead.
But when we move the loop into Rust and send just one call from Python, Rust blows Python away in speed, showing how calling patterns matter. Wrapping Rust like this is neat, and it lets you keep your Python easy for teams to maintain, while still getting the speed benefits from Rust. You could do the same thing with C, but Rust also helps avoid common bugs.
You can do similar stuff with JavaScript by compiling Rust to Wasm, but for now, this Python and Rust setup gives you the best of both worlds: Python’s simplicity and Rust’s performance. In the end, we see that when you use Rust smartly, doing heavy work inside Rust, not in Python loops, Python becomes much faster, and that is just cool.
Информация по комментариям в разработке