Use Cython to speed up python code

Posted by K.WANG on November 14, 2017

Cython is able to speed up python code.

It can automatically convert python function to C language, and compile to a lib which could be imported directly by python.

Let’s knock the door!

1 Installation

conda install cython

2 Hello World

  • write one-line python code to “helloworld.pyx”:

    print “Hello World”

  • create a python code to compile this pyx file. Generally, we named it as “setup.py”, which is similar to setuptools:

      from distutils.core import setup
      from Cython.Build import cythonize
    	
      setup(
          ext_modules = cythonize("helloworld.pyx")
      )
    	
    
  • use terminal to compile:

    python setup.py build_ext –inplace

  • We can include this function like python lib:

      import helloworld
    

    It will print out “Hello World”.

3 Details

See: http://docs.cython.org/en/latest/