Run python code hundreds of times faster
Running python code using Cython
[Cython] is a programming language that makes writing C extensions for the Python language as easy as Python itself.
It aims to become a superset of the [Python] language which gives it high-level, object-oriented, functional, and dynamic programming.
Its main feature on top of these is support for optional static type declarations as part of the language. The source code gets translated into optimized C/C++ code and compiled as Python extension modules.
This allows for both very fast program execution and tight integration with external C libraries, while keeping up the high programmer productivity for which the Python language is well known.
In this article i’ll show to integrate python with Cython, this example will show very simple code to sum number.
- First install Cython module using this command pip install Cython
- Then test if C compiler is already installed by typing gcc — help
- I’ll create new file called example_py.py and add this code, this is an code to add number based on range number.
- Then i created another file called example_cy.pyx and translate this simple code to cpdef you can see in this reference.
- To create executable shared object or .so file you need to create new file called setup.py, and add .pyx file in this installer file.
- So project folder will looks like something like this
- Then execute this command to generate shared object file or .so file, python setup.py build_ext — inplace
- So now project directory will looks like this, this command will generate shared object that we will use later.
- To test our Cython function you can access like this, create new file called testing_example_cy.py and adding this code to testing our Cython function, in this code we will try to sum add number for given specified parameter number.
- Final project directory will looks like this
- Then execute this file by using common command to execute python script, in this module so amazing that this code is run pretty fast 🚀. How amazing that.
- The last things is we will create file for testing this both method, first method in python file and second is method from Cython shared object, So create another file called testing_example.py, here we used python module called timeit to see their different executing time.
- Then this is an result, so amazing that this function is blazingly fast than common python script.
See that our Cython script is really really fast compare to common python script, this will very useful when you need to bridging module between python and C or need some heavy calculation in your python code that need fast execution time.
Basic Tutorial - Cython 3.0.0a10 documentation
As Cython can accept almost any valid python source file, one of the hardest things in getting started is just figuring…