Specifically, how can we make our SciPy code run faster? Well, there are two options: learn C or C++ (yuck) or use Cython (yay).
Let’s start with the obvious choice learning C or C++. This is a great option if you want to spend hours upon hours debugging memory leaks and segmentation faults while trying to figure out why your code isn’t working. Plus, who doesn’t love spending their weekends reading through dense documentation and struggling to understand the intricacies of pointers?
But wait! There’s another option Cython. With Cython, you can write Python code that looks like C code (but without all those ***** memory leaks and segmentation faults). And the best part is, it’s way easier to learn than C or C++. In fact, if you already know how to write basic Python code, you’re halfway there!
So why choose Cython over C or C++? Well, for starters, Cython gives us the best of both worlds we get the readability and ease-of-use of Python with the speed of C. And let me tell you, , that’s a match made in heaven!
But don’t just take our word for it. Here are some quotes from real people who have used Cython to improve their SciPy code:
“The biggest surprise (and of course this is Cython’s selling point) is how simple the interfacing between high level and low level code becomes, and the fact that it is all very robust.” Fredrik Johansson
“If you have a piece of Python that you need to run fast, then I would recommend you used Cython immediately. This means that I can exploit the beauty of Python and the speed of C together, and thats a match made in heaven.” Stavros
And let’s not forget about André Roberge who went from running single calculations in hours to seconds with Cython! That’s right , we’re talking about a reduction by a factor of 100. Who needs C or C++ when you have that kind of performance boost?
But don’t just take our word for it let’s look at some numbers. According to the Cython website, “Cython can give you up to a 5x speedup over pure Python.” And if that’s not enough, here are some real-world examples:
– In one case study, using Cython instead of C resulted in a 20% improvement in performance.
– Another study found that using Cython for matrix multiplication resulted in a 15x speedup over pure Python.
– And let’s not forget about the spaCy project which uses clean but efficient Cython code to manage both low level details and high-level Python API in a single codebase.
And who knows? Maybe one day we’ll all be able to say goodbye to those ***** memory leaks and segmentation faults for good.