It introduces how to make Python as fast as C by Cython at Taipei.py [1], COSCUP 2014 [2], Tainan.py [3], Taipei.py 2015 [4], Kaohsiung Python Meetup [5].
[1]: http://www.meetup.com/Taipei-py/events/169077442/
[2]: http://coscup.org/2014
[3]: http://www.meetup.com/Tainan-py-Python-Tainan-User-Group/events/219957183/
[4]: http://www.meetup.com/Taipei-py/events/222038313/
[5]: http://www.meetup.com/Kaohsiung-Python-Meetup/events/229978032/
2. Mosky
➤ Python Charmer at Pinkoi
➤ has spoken at 10+ conferences
➤ TEDxNTUST 2015
➤ PyCons in TW/JP/SG/HK
➤ etc.
➤ has taught Python for 100+ hours
➤ has serval Python packages
➤ MoSQL, Clime, etc.
➤ http://mosky.tw/
2
5. Cython
➤ Cython is a source-to-source compiler (aka. transcompiler).
➤ Cython is a superset of Python.
➤ Provides optional static type declarations.
➤ Makes writing C extensions for Python easier.
➤ Makes Python program faster by pre-compiling and
static type.
➤ Sometimes faster by orders of magnitude
5
9. Install Cython
➤ Recommend to use PIP:
➤ sudo pip install cython
➤ Other:
➤ http://docs.cython.org/src/quickstart/install.html
9
10. The setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'cython-lab',
ext_modules = cythonize('*.pyx'),
)
10
30. Overflow
➤ Static types may also overflow in Cython silently.
➤ Try to make an overflow!
➤ Hint:
➤ http://j.mp/test_overflow_in_c_c
➤ Ans:
➤ http://j.mp/overflow_in_pyx_pyx
30
31. Functions
➤ Write three functions
defined in
def, cdef, and cpdef.
➤ Try to call them in
➤ the same file,
➤ another .pyx file,
➤ and a .py file.
➤ Hints:
➤ Refer to the table,
“Function Visibility”.
➤ http://j.mp/
lib_in_pyx_pyx
➤ Ans:
➤ http://j.mp/
use_lib_in_pyx_pyx
➤ http://j.mp/
test_lib_in_pyx_py
31
32. Using C Function
➤ Try to use the functions in C.
➤ Playing with fork, the system call, may be fun.
➤ Hint:
➤ http://j.mp/test_fork_c
➤ Ans:
➤ http://j.mp/fork_in_pyx_pyx
32
34. cython -a
➤ cython -a NAME.pyx
➤ open NAME.html
➤ Lines are colored according to
the level of “typedness” –
white lines translates to pure
C without any Python API
calls.
34
42. Other Solutions
➤ Boost.Python — exposes C++ to Python
➤ Numba — compiles annotated code into LLVM by JIT
compiler
➤ PyPy — speeds up existent code by JIT compiler
➤ NumPy or Blaze — provides efficient array
➤ SciPy — provides fast scientific computing
42
43. Cool Down
➤ Algorithm still does matter in any case.
➤ Profile your program.
➤ Consider the portability — you are writing C program!
➤ Consider the improvement is enough or not.
➤ Then pick the most suitable tools.
43