Using Cython To Speed Up Numerical Python Programs
Using Cython To Speed Up Numerical Python Programs
1
INTRODUCTION:
•There is one major concern when using Python for scientific computations, namely the possible
loss of computational speed.
•Cython is a new extension of the Python language that aims at making the integration of C
and Python.
•Cython does not simply translate Python code to C code. Instead, it uses the Python run-time
environment, compiling everything directly to machine code.
2
CYTHON EXAMPLE:
•The following is simple code for numerical integration using the Trapezoidal rule. The Python
version looks like:
3
CYTHON EXAMPLE:
•This code runs fine with Cython, but in order to get a speed-up, we need to statically declare types
using the cdef keyword.
•The following Cython code runs about 30 times faster than the Python code:
4
CYTHON EXAMPLE:
•Functions defined with def and cdef can call each other within the Cython code, but functions defined
with cdef cannot be called directly from Python.
•So one either has to use a function defined with the keyword def, or another keyword cpdef indicating
that the function is to be used both as a Python and a Cython function.
5
CONCLUSION:
•Cython is a new, user-friendly alternative to mixing Python with Fortran, C, or C++ code.
• These constructs automatically move large parts of the calculation to assembly code.
•The performance is almost as good as that of using Fortran, C, or C++ from Python, but
Cython seems considerably easier to work with.
6
REFERENCES:
• D. Beazley et al. SWIG: Simplified wrapper and interface generator http://www.swig.org.
• Boost C++ libraries http://boost.org/libs.
• X. Cai and H. P. Langtangen Parallelizing PDE solvers using the Python programming language
In A. M. Bruaset and A. Tveito, editors, Numerical Solution of Partial Differential Equations on
Parallel Computers, volume 51 of Lecture Notes in Computational Science and Engineering, pages
295–325. Springer, 2006.
• X. Cai, H. P. Langtangen and H. Moe On the performance of the Python programming language
for serial and parallel scientific computations Scientific Programming, vol.13(1), 31–56, 2005.