Cython - Making Python as Fast as C

117
CYTHON — MAKING PYTHON AS FAST AS C Mosky

description

It introduces how to make Python as fast as C by Cython at Taipei.py [1], COSCUP 2014 [2], Tainan.py [3], and Taipei.py 2015 [4]. [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/

Transcript of Cython - Making Python as Fast as C

Page 1: Cython - Making Python as Fast as C

CYTHON — MAKING PYTHON AS FAST AS CMosky

Page 2: Cython - Making Python as Fast as C

MOSKY

2

Page 3: Cython - Making Python as Fast as C

MOSKY

Python Charmer at Pinkoi

2

Page 4: Cython - Making Python as Fast as C

MOSKY

Python Charmer at Pinkoi

An author of the Python Packages

MoSQL, Clime, … and more

2

Page 5: Cython - Making Python as Fast as C

MOSKY

Python Charmer at Pinkoi

An author of the Python Packages

MoSQL, Clime, … and more

A speaker of the conferences, PyCon TW/JP mostly.

2

Page 6: Cython - Making Python as Fast as C

MOSKY

Python Charmer at Pinkoi

An author of the Python Packages

MoSQL, Clime, … and more

A speaker of the conferences, PyCon TW/JP mostly.

A Python instructor

2

Page 7: Cython - Making Python as Fast as C

MOSKY

Python Charmer at Pinkoi

An author of the Python Packages

MoSQL, Clime, … and more

A speaker of the conferences, PyCon TW/JP mostly.

A Python instructor

mosky.tw2

Page 8: Cython - Making Python as Fast as C

OUTLINE

3

Page 9: Cython - Making Python as Fast as C

OUTLINE

Introduction

3

Page 10: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

3

Page 11: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

Foundation

3

Page 12: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

Foundation

Practicing

3

Page 13: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

Foundation

Practicing

Tips

3

Page 14: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

Foundation

Practicing

Tips

Uncovered Topics

3

Page 15: Cython - Making Python as Fast as C

OUTLINE

Introduction

Setup

Foundation

Practicing

Tips

Uncovered Topics

Is Cython the best solution?

3

Page 16: Cython - Making Python as Fast as C

INTRODUCTION

Page 17: Cython - Making Python as Fast as C

CYTHON

5

Page 18: Cython - Making Python as Fast as C

CYTHON

Cython is a source-to-source compiler (aka. transcompiler).

5

Page 19: Cython - Making Python as Fast as C

CYTHON

Cython is a source-to-source compiler (aka. transcompiler).

Cython is a superset of Python.

5

Page 20: Cython - Making Python as Fast as C

CYTHON

Cython is a source-to-source compiler (aka. transcompiler).

Cython is a superset of Python.

Provides optional static type declarations.

5

Page 21: Cython - Making Python as Fast as C

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.

5

Page 22: Cython - Making Python as Fast as C

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

Page 23: Cython - Making Python as Fast as C

6

Page 24: Cython - Making Python as Fast as C

6

.pyx

Page 25: Cython - Making Python as Fast as C

6

.pyx .c

Cython

Page 26: Cython - Making Python as Fast as C

6

.pyx .c

Cython

C compiler

.so

Page 27: Cython - Making Python as Fast as C

6

.pyx .c

Cython

C compiler

.so .py

Page 28: Cython - Making Python as Fast as C

6

.pyx .c

Cython

C compiler

.so .py

Python

Page 29: Cython - Making Python as Fast as C

6

.pyx .c

Cython

C compiler

import.so .py

Python

Page 30: Cython - Making Python as Fast as C

SETUP

Page 31: Cython - Making Python as Fast as C

INSTALL C COMPILER

8

Page 32: Cython - Making Python as Fast as C

INSTALL C COMPILER

Mac:

xcode-select --install

8

Page 33: Cython - Making Python as Fast as C

INSTALL C COMPILER

Mac:

xcode-select --install

Ubuntu / Debian:

sudo apt-get install build-essential

8

Page 34: Cython - Making Python as Fast as C

INSTALL C COMPILER

Mac:

xcode-select --install

Ubuntu / Debian:

sudo apt-get install build-essential

Other:

http://docs.cython.org/src/quickstart/install.html8

Page 35: Cython - Making Python as Fast as C

INSTALL CYTHON

9

Page 36: Cython - Making Python as Fast as C

INSTALL CYTHON

Recommend to use PIP:

sudo pip install cython

9

Page 37: Cython - Making Python as Fast as C

INSTALL CYTHON

Recommend to use PIP:

sudo pip install cython

Other:

http://docs.cython.org/src/quickstart/install.html

9

Page 38: Cython - Making Python as Fast as C

THE SETUP.PY

from distutils.core import setup

from Cython.Build import cythonize

!

setup(

    name = 'cython-lab',

    ext_modules = cythonize('*.pyx'),

)10

Page 39: Cython - Making Python as Fast as C

THE HELLO_CYTHON.PYX

print 'Hello Cython!'

11

Page 40: Cython - Making Python as Fast as C

BUILD

12

Page 41: Cython - Making Python as Fast as C

BUILD

Into package folder for development:

python setup.py build_ext --inplace

12

Page 42: Cython - Making Python as Fast as C

BUILD

Into package folder for development:

python setup.py build_ext --inplace

Into system for production:

python setup.py install

12

Page 43: Cython - Making Python as Fast as C

BUILD

Into package folder for development:

python setup.py build_ext --inplace

Into system for production:

python setup.py install

If clang: error: unknown argument: '-mno-fused-madd',

export CFLAGS=-Qunused-arguments12

Page 44: Cython - Making Python as Fast as C

FOUNDATION— the difference of Cython and Python

Page 45: Cython - Making Python as Fast as C

DEFINE STATIC TYPES

cdef int i, j, k

cdef float f, g[42], *h

14

Page 46: Cython - Making Python as Fast as C

cdef struct Grail:

int age

float volume

!

cdef union Food:

char* spam

float* eggs

!

cdef enum CheeseType:

cheddar, edam,

camembert

!

cdef enum CheeseState:

hard = 1

soft = 2

runny = 315

Page 47: Cython - Making Python as Fast as C

ctypedef unsigned long ULong

!

ctypedef int* IntPtr

16

Page 48: Cython - Making Python as Fast as C

cdef struct Point:

int x

int y

!

# either `struct` or `ctypedef` is not need

cdef Point p

17

Page 49: Cython - Making Python as Fast as C

cdef:

struct Point:

int x

int y

!

Point p

18

Page 50: Cython - Making Python as Fast as C

DEFINE FUNCTION

def say_hello(name='World'):

return 'Hello, %s!' % name

!

cdef say_hello(name='World'):

return 'Hello, %s!' % name19

Page 51: Cython - Making Python as Fast as C

cdef say_hello(object name='World'):

return 'Hello, %s!' % name

!

cdef say_hello(char* name='World'):

return 'Hello, %s!' % name

20

Page 52: Cython - Making Python as Fast as C

cdef int add(int a, int b):

return a+b

!

cpdef say_hello(char* name='World'):

return 'Hello, %s!' % name

21

Page 53: Cython - Making Python as Fast as C

.PXD EXPOSES CDEF FUNC.

# mylib.pxd

cdef say_hello(char* name=?)

!

# another.pyx

from mylib cimport say_hello22

Page 54: Cython - Making Python as Fast as C

USING C LIB.

from libc.math cimport sin

# or

cdef extern from "math.h":

double sin(double x)

23

Page 55: Cython - Making Python as Fast as C

FUNCTION VISIBILITY

24

SAME FILE

OTHER .PYX .PY

FUNC. IN .H/.C

Visible directly

Visible via cdef extern

InvisibleCDEF

Visible via .pxd & cimport

CPDEFVisible

via importDEF

Page 56: Cython - Making Python as Fast as C

BINDING DURING

25

SAME FILE

OTHER .PYX .PY

FUNC. IN .H/.C

compile-time

compile-time xCDEF

CPDEF

run-timeDEF

Page 57: Cython - Making Python as Fast as C

TYPE CONVERSIONS

26

C FROM PY TO PY

[UNSIGNED] CHAR/SHORT INT

int/long

intLONG

UNSIGNED INT/LONG

long[UNSIGNED] LONG LONG

Page 58: Cython - Making Python as Fast as C

27

C FROM PY TO PY

FLOAT/DOUBLE

int/long/float float

LONG DOUBLE

CHAR* str/bytes

STRUCT dict

Page 59: Cython - Making Python as Fast as C

PRACTICING

Page 60: Cython - Making Python as Fast as C

SUGGESTION

29

Page 61: Cython - Making Python as Fast as C

SUGGESTION

LIB_NAME.pyx

has an execute_self_tests function

29

Page 62: Cython - Making Python as Fast as C

SUGGESTION

LIB_NAME.pyx

has an execute_self_tests function

test_LIB_NAME.py

call the execute_self_tests function

29

Page 63: Cython - Making Python as Fast as C

OVERFLOW

30

Page 64: Cython - Making Python as Fast as C

OVERFLOW

Static types may also overflow in Cython silently.

30

Page 65: Cython - Making Python as Fast as C

OVERFLOW

Static types may also overflow in Cython silently.

Try to make an overflow!

30

Page 66: Cython - Making Python as Fast as C

OVERFLOW

Static types may also overflow in Cython silently.

Try to make an overflow!

Hint:

http://j.mp/test_overflow_in_c_c

30

Page 67: Cython - Making Python as Fast as C

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

Page 68: Cython - Making Python as Fast as C

FUNCTIONS

31

Page 69: Cython - Making Python as Fast as C

FUNCTIONS

Write three func. defined in def, cdef, and cpdef.

31

Page 70: Cython - Making Python as Fast as C

FUNCTIONS

Write three func. defined in def, cdef, and cpdef.

Try to call them in

the same file,

another .pyx file,

and a .py file.

31

Page 71: Cython - Making Python as Fast as C

FUNCTIONS

Write three func. 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

31

Page 72: Cython - Making Python as Fast as C

FUNCTIONS

Write three func. 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

Page 73: Cython - Making Python as Fast as C

USING C FUNCTION

32

Page 74: Cython - Making Python as Fast as C

USING C FUNCTION

Try to use the functions in C.

32

Page 75: Cython - Making Python as Fast as C

USING C FUNCTION

Try to use the functions in C.

Playing with fork, the system call, may be fun.

32

Page 76: Cython - Making Python as Fast as C

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

32

Page 77: Cython - Making Python as Fast as C

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

Page 78: Cython - Making Python as Fast as C

TIPS

Page 79: Cython - Making Python as Fast as C

CYTHON -A

34

Page 80: Cython - Making Python as Fast as C

CYTHON -A

cython -a NAME.pyx

34

Page 81: Cython - Making Python as Fast as C

CYTHON -A

cython -a NAME.pyx

open NAME.html

34

Page 82: Cython - Making Python as Fast as C

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

Page 83: Cython - Making Python as Fast as C

PYXIMPORT

import pyximport; pyximport.install()

import my_pyx_lib # compile .pyx into .so

!

# or

pyximport.install(pyimport=True)

import my_py_lib # compile .py into .so35

Page 84: Cython - Making Python as Fast as C

UNCOVERED TOPICS

Page 85: Cython - Making Python as Fast as C

UNCOVERED TOPICS

37

Page 86: Cython - Making Python as Fast as C

UNCOVERED TOPICS

Differences between C and Cython expressions

http://docs.cython.org/src/userguide/language_basics.html#differences-between-c-and-cython-expressions

37

Page 87: Cython - Making Python as Fast as C

UNCOVERED TOPICS

Differences between C and Cython expressions

http://docs.cython.org/src/userguide/language_basics.html#differences-between-c-and-cython-expressions

Propagating Exceptions in cdef

http://docs.cython.org/src/userguide/language_basics.html#error-return-values

37

Page 88: Cython - Making Python as Fast as C

38

Page 90: Cython - Making Python as Fast as C

Extension Type — cdef class

http://docs.cython.org/src/userguide/extension_types.html

Generic programming using Cython's Template

http://docs.cython.org/src/userguide/fusedtypes.html

38

Page 91: Cython - Making Python as Fast as C

Extension Type — cdef class

http://docs.cython.org/src/userguide/extension_types.html

Generic programming using Cython's Template

http://docs.cython.org/src/userguide/fusedtypes.html

Conditional Compilation

http://docs.cython.org/src/userguide/language_basics.html#conditional-compilation

38

Page 92: Cython - Making Python as Fast as C

39

Page 94: Cython - Making Python as Fast as C

Profiling

http://docs.cython.org/src/tutorial/profiling_tutorial.html

Parallelism (No GIL + OpenMP)

http://docs.cython.org/src/userguide/parallelism.html

39

Page 95: Cython - Making Python as Fast as C

Profiling

http://docs.cython.org/src/tutorial/profiling_tutorial.html

Parallelism (No GIL + OpenMP)

http://docs.cython.org/src/userguide/parallelism.html

Using C++ in Cython

http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html

39

Page 96: Cython - Making Python as Fast as C

IS CYTHON THE BEST SOLUTION?

Page 97: Cython - Making Python as Fast as C

PYTHON COMMUNITY

IS DORAEMON!

Page 98: Cython - Making Python as Fast as C

OTHER SOLUTIONS

42

Page 99: Cython - Making Python as Fast as C

Boost.Python — exposes C++ to Python

OTHER SOLUTIONS

42

Page 100: Cython - Making Python as Fast as C

Boost.Python — exposes C++ to Python

Numba — compiles annotated code into LLVM by JIT compiler

OTHER SOLUTIONS

42

Page 101: Cython - Making Python as Fast as C

Boost.Python — exposes C++ to Python

Numba — compiles annotated code into LLVM by JIT compiler

PyPy — speeds up existent code by JIT compiler

OTHER SOLUTIONS

42

Page 102: Cython - Making Python as Fast as C

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

OTHER SOLUTIONS

42

Page 103: Cython - Making Python as Fast as C

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

OTHER SOLUTIONS

42

Page 104: Cython - Making Python as Fast as C

COOL DOWN

43

Page 105: Cython - Making Python as Fast as C

COOL DOWN

Algorithm still does matter in any case.

43

Page 106: Cython - Making Python as Fast as C

COOL DOWN

Algorithm still does matter in any case.

Profile your program.

43

Page 107: Cython - Making Python as Fast as C

COOL DOWN

Algorithm still does matter in any case.

Profile your program.

Consider the portability — you are writing C program!

43

Page 108: Cython - Making Python as Fast as C

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.

43

Page 109: Cython - Making Python as Fast as C

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

Page 110: Cython - Making Python as Fast as C

DEMO?

Page 111: Cython - Making Python as Fast as C

ENDING

Page 112: Cython - Making Python as Fast as C

ENDING

46

Page 113: Cython - Making Python as Fast as C

ENDING

cdef

static types

functions

extern for C func.

46

Page 114: Cython - Making Python as Fast as C

ENDING

cdef

static types

functions

extern for C func.

.pxd exposes cdef func.

46

Page 115: Cython - Making Python as Fast as C

ENDING

cdef

static types

functions

extern for C func.

.pxd exposes cdef func.

Tips

46

Page 116: Cython - Making Python as Fast as C

ENDING

cdef

static types

functions

extern for C func.

.pxd exposes cdef func.

Tips

mosky.tw

46

Page 117: Cython - Making Python as Fast as C

ENDING

cdef

static types

functions

extern for C func.

.pxd exposes cdef func.

Tips

mosky.tw

Any question?

46