a lot of people use Cython to compile their python code in C for performance gains. It’s petty easy to do and might be something that you want to take advantage of.
Make sure you pip install Cython first.
The overall process goes like this.
- Bring the parts of your code you want to convert to c into a separate file
- Give type information and let Cython know what you want to use in Python and what you don’t.
- compile the separate file using a setup.py file
For this example, let’s say we want to compile this function into C
x = 0for i in range(1,11):
The first thing we need to do is move this from a .py file into a .pyx file, which is what Cython uses. Now we are going to give type information to our variables
Want to read this story later? Save it in Journal.
in Cython, there are three def statements
- cdef: declaring something that is only going to be used in c(like the variables inside our function)
- pdef: declaring something that is only going to be used in Python
- cpdef: declaring something this going to be used in both
cpdef int AddToTen():
cdef int x = 0
cdef int ifor i in range(1,11):
Since I’m not going to call the variables inside our function in Python, I used cdef, but for the function itself, I used cpdef
Also, notice we typed the I in the for loop and the function since it returns an int.
Now we have to compile our .pyx. In a separate file (mine is named setup.py), write the following code.
from distutils.core import setup
from Cython.Build import cythonizesetup(ext_modules = cythonize('The_Name_Of_Your_Pyx_Here.pyx'))
Finally, in terminal(make sure you are in the same folder), run the line
python setup.py build_ext --inplace
This should’ve compiled your pyx, and you should see a file of the same name with the extension .c instead of pyx
You can now import your c functions into local python files, given that you used cpdef, just by import’ name of your file’. IDEs tend to give me import errors even though they imported fine. You can also import python libraries into the pyx file, but in my experience, it performs the same as it would in Python.