SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
Cython — 

Making Python as Fast as C
Mosky
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
Outline
1. Introduction
2. Setup
3. Foundation
4. Practicing
5. Tips
6. Uncovered Topics
7. Is Cython the best solution?
3
Introduction
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
.pyx .c
Cython
C compiler
import.so .py
Python
Setup
Install C Compiler
➤ Mac:
➤ xcode-select --install
➤ Ubuntu / Debian:
➤ sudo apt-get install build-essential
➤ Other:
➤ http://docs.cython.org/src/quickstart/install.html
8
Install Cython
➤ Recommend to use PIP:
➤ sudo pip install cython
➤ Other:
➤ http://docs.cython.org/src/quickstart/install.html
9
The setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(
    name = 'cython-lab',
    ext_modules = cythonize('*.pyx'),
)
10
The hello_cython.pyx
print 'Hello Cython!'
11
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-arguments
12
Foundation
Define Static Types
cdef int i, j, k
cdef float f, g[42], *h
14
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 = 3
15
ctypedef unsigned long ULong
ctypedef int* IntPtr
16
cdef struct Point:
int x
int y
# either `struct` or `ctypedef` is not need
cdef Point p
17
cdef:
struct Point:
int x
int y
Point p
18
Define Function
def say_hello(name='World'):
return 'Hello, %s!' % name
cdef say_hello(name='World'):
return 'Hello, %s!' % name
19
cdef say_hello(object name='World'):
return 'Hello, %s!' % name
cdef say_hello(char* name='World'):
return 'Hello, %s!' % name
20
cdef int add(int a, int b):
return a+b
cpdef say_hello(char* name='World'):
return 'Hello, %s!' % name
21
.pxd Exposes cdef Func
# mylib.pxd
cdef say_hello(char* name=?)
# another.pyx
from mylib cimport say_hello
22
Using C Lib
from libc.math cimport sin
# or
cdef extern from "math.h":
double sin(double x)
23
Function Visibility
24
Same 

File
Other
.pyx
.py
Func in .h/.c
Visible

directly
Visible

via cdef extern
Invisible
cdef
Visible

via .pxd &
cimport
cpdef
Visible

via import
def
Binding During
25
Same 

File
Other
.pyx
.py
Func in .h/.c
compile-time
compile-time x
cdef
cpdef
run-time
def
Type Conversions
26
C From PY To PY
[unsigned] 

char/short int
int/long
int
long
unsigned
int/long
long
[unsigned]
long long
C From PY To PY
float/double
int/long/float float
long double
char* str/bytes
struct dict
Practicing
Suggestions
➤ LIB_NAME.pyx
➤ has an execute_self_tests function
➤ test_LIB_NAME.py
➤ call the execute_self_tests function
29
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
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
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
Tips
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
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 .so
35
Uncovered Topics
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
➤ 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
➤ 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
Is Cython 

the best solution?
PYTHON 

COMMUNITY 

IS 

DORAEMON!
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
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
Ending
Ending
➤ cdef
➤ static types
➤ functions
➤ extern for C functions
➤ .pxd exposes cdef functions
➤ Tips
➤ mosky.tw
➤ Any question?
45

Mais conteúdo relacionado

Destaque

Simple Belief - Mosky @ TEDxNTUST 2015
Simple Belief - Mosky @ TEDxNTUST 2015Simple Belief - Mosky @ TEDxNTUST 2015
Simple Belief - Mosky @ TEDxNTUST 2015Mosky Liu
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal PythonTaras Lyapun
 
Minimal MVC in JavaScript
Minimal MVC in JavaScriptMinimal MVC in JavaScript
Minimal MVC in JavaScriptMosky Liu
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to ClimeMosky Liu
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cythonAtsuo Ishimoto
 
Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with pythonPatrick Vergain
 
なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?Aki Ariga
 
NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門Shiqiao Du
 
Slack presentation
Slack presentationSlack presentation
Slack presentationblevz
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 

Destaque (12)

Simple Belief - Mosky @ TEDxNTUST 2015
Simple Belief - Mosky @ TEDxNTUST 2015Simple Belief - Mosky @ TEDxNTUST 2015
Simple Belief - Mosky @ TEDxNTUST 2015
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal Python
 
Minimal MVC in JavaScript
Minimal MVC in JavaScriptMinimal MVC in JavaScript
Minimal MVC in JavaScript
 
Introduction to Clime
Introduction to ClimeIntroduction to Clime
Introduction to Clime
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
 
Pycon UA 2016
Pycon UA 2016Pycon UA 2016
Pycon UA 2016
 
Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with python
 
なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?なぜ科学計算にはPythonか?
なぜ科学計算にはPythonか?
 
NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門NumPyが物足りない人へのCython入門
NumPyが物足りない人へのCython入門
 
Slack presentation
Slack presentationSlack presentation
Slack presentation
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 

Mais de Mosky Liu

Statistical Regression With Python
Statistical Regression With PythonStatistical Regression With Python
Statistical Regression With PythonMosky Liu
 
Practicing Python 3
Practicing Python 3Practicing Python 3
Practicing Python 3Mosky Liu
 
Data Science With Python
Data Science With PythonData Science With Python
Data Science With PythonMosky Liu
 
Hypothesis Testing With Python
Hypothesis Testing With PythonHypothesis Testing With Python
Hypothesis Testing With PythonMosky Liu
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrencyMosky Liu
 
Dive into Pinkoi 2013
Dive into Pinkoi 2013Dive into Pinkoi 2013
Dive into Pinkoi 2013Mosky Liu
 
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013Mosky Liu
 
MoSQL: More than SQL, but less than ORM
MoSQL: More than SQL, but less than ORMMoSQL: More than SQL, but less than ORM
MoSQL: More than SQL, but less than ORMMosky Liu
 

Mais de Mosky Liu (8)

Statistical Regression With Python
Statistical Regression With PythonStatistical Regression With Python
Statistical Regression With Python
 
Practicing Python 3
Practicing Python 3Practicing Python 3
Practicing Python 3
 
Data Science With Python
Data Science With PythonData Science With Python
Data Science With Python
 
Hypothesis Testing With Python
Hypothesis Testing With PythonHypothesis Testing With Python
Hypothesis Testing With Python
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
 
Dive into Pinkoi 2013
Dive into Pinkoi 2013Dive into Pinkoi 2013
Dive into Pinkoi 2013
 
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
MoSQL: More than SQL, but Less than ORM @ PyCon APAC 2013
 
MoSQL: More than SQL, but less than ORM
MoSQL: More than SQL, but less than ORMMoSQL: More than SQL, but less than ORM
MoSQL: More than SQL, but less than ORM
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 

Último (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 

Cython - Making Python as Fast as C

  • 1. Cython — 
 Making Python as Fast as C Mosky
  • 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
  • 3. Outline 1. Introduction 2. Setup 3. Foundation 4. Practicing 5. Tips 6. Uncovered Topics 7. Is Cython the best solution? 3
  • 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
  • 8. Install C Compiler ➤ Mac: ➤ xcode-select --install ➤ Ubuntu / Debian: ➤ sudo apt-get install build-essential ➤ Other: ➤ http://docs.cython.org/src/quickstart/install.html 8
  • 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
  • 12. 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-arguments 12
  • 14. Define Static Types cdef int i, j, k cdef float f, g[42], *h 14
  • 15. 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 = 3 15
  • 16. ctypedef unsigned long ULong ctypedef int* IntPtr 16
  • 17. cdef struct Point: int x int y # either `struct` or `ctypedef` is not need cdef Point p 17
  • 19. Define Function def say_hello(name='World'): return 'Hello, %s!' % name cdef say_hello(name='World'): return 'Hello, %s!' % name 19
  • 20. cdef say_hello(object name='World'): return 'Hello, %s!' % name cdef say_hello(char* name='World'): return 'Hello, %s!' % name 20
  • 21. cdef int add(int a, int b): return a+b cpdef say_hello(char* name='World'): return 'Hello, %s!' % name 21
  • 22. .pxd Exposes cdef Func # mylib.pxd cdef say_hello(char* name=?) # another.pyx from mylib cimport say_hello 22
  • 23. Using C Lib from libc.math cimport sin # or cdef extern from "math.h": double sin(double x) 23
  • 24. Function Visibility 24 Same 
 File Other .pyx .py Func in .h/.c Visible
 directly Visible
 via cdef extern Invisible cdef Visible
 via .pxd & cimport cpdef Visible
 via import def
  • 25. Binding During 25 Same 
 File Other .pyx .py Func in .h/.c compile-time compile-time x cdef cpdef run-time def
  • 26. Type Conversions 26 C From PY To PY [unsigned] 
 char/short int int/long int long unsigned int/long long [unsigned] long long
  • 27. C From PY To PY float/double int/long/float float long double char* str/bytes struct dict
  • 29. Suggestions ➤ LIB_NAME.pyx ➤ has an execute_self_tests function ➤ test_LIB_NAME.py ➤ call the execute_self_tests function 29
  • 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
  • 33. Tips
  • 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
  • 35. 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 .so 35
  • 37. 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
  • 38. ➤ 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
  • 39. ➤ 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
  • 40. Is Cython 
 the best solution?
  • 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
  • 45. Ending ➤ cdef ➤ static types ➤ functions ➤ extern for C functions ➤ .pxd exposes cdef functions ➤ Tips ➤ mosky.tw ➤ Any question? 45