SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
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

Contenu connexe

En vedette

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
 

En vedette (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
 

Plus 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
 

Plus 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
 

Dernier

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
+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
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Dernier (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
+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...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

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