My Coding >
Programming language >
Python >
Accelerating Python >
How to accelerate math calculations with Numba and Cython
How to accelerate math calculations with Numba and CythonPython is an interpretation that results in a pretty slow execution of a simple code. To accelerate it, it is possible to use some precompilation techniques. In this tutorial, I will show you how to use Numba and Cython libraries to accelerate linear mathematical calculations up to 20 times. You should understand that the acceleration will be different in every case. Fibanacci numbers in pythonI have already shown, how to calculate Fibonacci numbers. For this example, I will use very simple code in the file fib.py:
All these codes I will run from the main file run.py:
On my computer, this code was executed within 15.07 seconds. Numba optimisationNumba codingFor linear, non-vectorised operations, Numba can do just-in-time optimisation while saving time on permanent interpretation of the source code. For this code i will create file nfib.py:
So, the only changes are to import library numba and then use @numba.njit in front of the function to be optimised. The usage is the same
Numba accelerationThe overall acceleration in this case was 12x!!! Cython optimisationOptimisation for proper C Cython is more complicated and it requires some knowledge of C language. Cython codingThe the Cython code will be written in the cfib.pyx file.
It is important to have a proper C definition of all variables used. Then, it is necessary to compile it with the command:
The options mean that we will build in place our code with detailed annotations. Analysis of the annotation file will allow you to understand, how effectively your code is translated. The calling of this code is identical to our other functions
Cython accelerationThe overall acceleration achieved by using the Cython library is 20x! Python vs Numba vs CythonVariablesIt is important to remember, that in Python, variables can be very long. In Numba and Cython, variables are limited by the C definition! In fact, Numba can work in Python and C mode: both jit and njit decorators can be used for JIT compilation, but njit is a shortcut specifically for cases where you want to ensure that the function is compiled in the nopython mode. Choosing Between Numba and Cython:For quick and easy speedups with minimal modifications, especially for numerical code, Numba may be preferred. If you need more control over optimizations, integration with existing C code, or fine-tuned performance, Cython might be a better choice. Ultimately, the choice between Numba and Cython depends on your specific use case, development preferences, and the nature of the code you're working with.
|
Last 10 artitles
9 popular artitles
|
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |