There are three types when you define a function in cython, the general difference between these types are:
- def function is called from Python code with Python objects as arguments, returns a python object.
- cdef is used for Cython function that are intended to be pure ‘C’ function. All types must be declared and it is not visible to python code when import the module include this function
- cpdef functions combine both def and cdef features.
Here will give you a intuitive feeling to the performance if you write in different types.
a python file
a optimize file which contains different type of function
setup file for cyFibo.pyx
run the command below to generate the module can be called:
python setup.py build_ext –inplace
run these command under python3.5 to check the performance of these code
python -m timeit -s “import Fibo” “Fibo.fib(30)”
python -m timeit -s “import cyFibo” “cyFibo.fib(30)”
python -m timeit -s “import cyFibo” “cyFibo.fib_int(30)”
python -m timeit -s “import cyFibo” “cyFibo.fib_cdef(30)”
python -m timeit -s “import cyFibo” “cyFibo.fib_cpdef(30)”
Virtual Processors: 4
the best performance of each function is shown in this table:
It’s easy to have a conclusion that if we tell compiler the type of the variable and function, and call it from python, it will be fast.
There are some tips for improve the performance:
- do loops in cython and more loops more relative faster
- tell the compiler the type of the variables
- try to write the key algorithm in ‘pure’ c code and then give a wrapper make it can be called from python