SlideShare a Scribd company logo
1 of 11
INTRODUCTION TO
CYTHON
John
Saturday, December 21, 2013
Overview
• a superset of the Python language which give
high-level, OO functional, and dynamic
programming.
• The source code translate to optimized C/C++
code and compiled as Python extension
modules.
• One word, Cython is Python with C data
types.
Installing Cython
• Pythonxy already include Cython.
• Use easy_install or pip install Cython from
PYPI.
$ python easy_install.py Cython
$ pip install Cython
First example: Building a Cython
module “hello”
hello.pyx
def say_hello_to(name):
print (“Hello %s!” %
name)

setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("hello",
["hello.pyx"])]

Run command line build the module
$ python setup.py build_ext --inplace
--compiler=mingw32 --inplace
# How to run the function:
>>> from hello import say_hello_to
>>> say_hello_to(“John”)
Hello John

setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
Static type declarations
Cython can compile pure python code. To improve
performance, use cdef add static type declarations
# test1.pyx, 35% speedup
def f(x):
return x**2-x
def integrate_f(a, b, N):
s=0
dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s*dx

# 4 time speedup over python version
def f(double x):
return x**2-x
def integrate_f(double a, double b, int
N):
cdef int i
cdef double s, dx
s=0
dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s*dx
Typing function
#declare c-style function
150 times speedup
cdef double f(double x)
except ? -2:
return x**2 - x
>>> import hello
>>> hasattr(hello,'f')
False
# if use cpdef instead of cdef, a
Python wrapper is also created

annotation tell you why your
code take time
$ cython.py -a hello.pyx
a html (hello.html) is created,
Click the yellow, you will get
why the Python API is called
here
Calling C function
A complete list of these
cimport file see LibsitepackagesCythonIncludes

from libc.math cimport sin
cdef double f(double x):
return sin(x*x)

If Cython do not provide read-to-use
declaration, access C code by cdef

# instruct Cython generate C
code that include math.h
header file
# C compiler will see it at
compile time
cdef extern from “math.h”:
double sin(double)
cdef double f(double x):
return sin(x*x)
Using C libraries
Step 1: redefine .pxd head file

Step 2: create a pyx define
Queue class in Python

# file: cqueue.pxd
# copy most part of C head file here
cdef extern from "libcalg/queue.h":
ctypedef struct Queue:
pass
ctypedef void* QueueValue
Queue* queue_new()
void queue_free(Queue* queue)

# file: queue.pyx
cimport cqueue
cdef class Queue:
cdef cqueue.Queue
*_c_queue
def __cinit__(self):
self._c_queue =
cqueue.queue_new()
Using C libraries - cont
or step 3.2: include the lib in
step 3.1: change the setup.py
the option
$ CFLAGS="change
I/usr/local/otherdir/calg/include" 
ext_modules =
[Extension("queue
LDFLAGS="", ["queue.pyx"])]
L/usr/local/otherdir/calg/lib"  python
setup.py build_ext -i
to
ext_modules =
[ Extension("queu
e", ["queue.pyx"],
libraries=["calg"]) ]

calg lib see Simon Howard, C Algorithms library,
http://c-algorithms.sourceforge.net/
Using C++ in Cython
• Brief overview of C++ support in Cython(Cython
v0.13)
– C++ objects can now be dynamically allocated
with new and del keywords.
– C++ objects can be stack-allocated.
– C++ classes can be declared with the new
keyword cppclass.
– Templated classes are supported.
– Overloaded functions are supported.
– Overloading of C++ operators (such as operator+,
operator[],...) is supported.
Review of this Slides
1. introduce the Cython
2. How to install Cython
3. An example show how to compile a Cython
project
4. Optimize the pure Python code with Cython
5. Call C function in Python code
6. Use C library in Python code

More Related Content

What's hot

Android audio system(audioflinger)
Android audio system(audioflinger)Android audio system(audioflinger)
Android audio system(audioflinger)
fefe7270
 
Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)
fefe7270
 
Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)
fefe7270
 

What's hot (20)

Python in real world.
Python in real world.Python in real world.
Python in real world.
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Android audio system(audioflinger)
Android audio system(audioflinger)Android audio system(audioflinger)
Android audio system(audioflinger)
 
Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Debian Linux on Zynq (Xilinx ARM-SoC FPGA) Setup Flow (Vivado 2015.4)
Debian Linux on Zynq (Xilinx ARM-SoC FPGA) Setup Flow (Vivado 2015.4)Debian Linux on Zynq (Xilinx ARM-SoC FPGA) Setup Flow (Vivado 2015.4)
Debian Linux on Zynq (Xilinx ARM-SoC FPGA) Setup Flow (Vivado 2015.4)
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
What is Python? | Edureka
What is Python? | EdurekaWhat is Python? | Edureka
What is Python? | Edureka
 
Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)Android audio system(오디오 플링거 서비스 초기화)
Android audio system(오디오 플링거 서비스 초기화)
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? Edureka
 
SPI Drivers
SPI DriversSPI Drivers
SPI Drivers
 
Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)Android audio system(pcm데이터출력요청-서비스클라이언트)
Android audio system(pcm데이터출력요청-서비스클라이언트)
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Bd master guide extract encapsulated bios
Bd master guide extract encapsulated biosBd master guide extract encapsulated bios
Bd master guide extract encapsulated bios
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
08 android multimedia_framework_overview
08 android multimedia_framework_overview08 android multimedia_framework_overview
08 android multimedia_framework_overview
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편도커없이 컨테이너 만들기 1편
도커없이 컨테이너 만들기 1편
 

Similar to Introduction to cython

Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
meharikiros2
 

Similar to Introduction to cython (20)

Writing a Python C extension
Writing a Python C extensionWriting a Python C extension
Writing a Python C extension
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal Python
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
An Introduction to CMake
An Introduction to CMakeAn Introduction to CMake
An Introduction to CMake
 
Introduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationIntroduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimization
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
PyHEP 2018: Tools to bind to Python
PyHEP 2018:  Tools to bind to PythonPyHEP 2018:  Tools to bind to Python
PyHEP 2018: Tools to bind to Python
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.Net
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
SECCOM 2017 - Conan.io o gerente de pacote para C e C++
SECCOM 2017 - Conan.io o gerente de pacote para C e C++SECCOM 2017 - Conan.io o gerente de pacote para C e C++
SECCOM 2017 - Conan.io o gerente de pacote para C e C++
 
C - ISRO
C - ISROC - ISRO
C - ISRO
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptx
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
 
C++Basics2022.pptx
C++Basics2022.pptxC++Basics2022.pptx
C++Basics2022.pptx
 
ICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdfICT1002-W8-LEC-Introduction-to-C.pdf
ICT1002-W8-LEC-Introduction-to-C.pdf
 
C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...C++ helps you to format the I/O operations like determining the number of dig...
C++ helps you to format the I/O operations like determining the number of dig...
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
 
Digital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meetingDigital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meeting
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
 

More from John(Qiang) Zhang

A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modules
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
John(Qiang) Zhang
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
John(Qiang) Zhang
 

More from John(Qiang) Zhang (11)

Git and github introduction
Git and github introductionGit and github introduction
Git and github introduction
 
Python testing
Python  testingPython  testing
Python testing
 
Profiling in python
Profiling in pythonProfiling in python
Profiling in python
 
Introduction to jython
Introduction to jythonIntroduction to jython
Introduction to jython
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modules
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
 

Recently uploaded

Recently uploaded (20)

A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 

Introduction to cython

  • 2. Overview • a superset of the Python language which give high-level, OO functional, and dynamic programming. • The source code translate to optimized C/C++ code and compiled as Python extension modules. • One word, Cython is Python with C data types.
  • 3. Installing Cython • Pythonxy already include Cython. • Use easy_install or pip install Cython from PYPI. $ python easy_install.py Cython $ pip install Cython
  • 4. First example: Building a Cython module “hello” hello.pyx def say_hello_to(name): print (“Hello %s!” % name) setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension("hello", ["hello.pyx"])] Run command line build the module $ python setup.py build_ext --inplace --compiler=mingw32 --inplace # How to run the function: >>> from hello import say_hello_to >>> say_hello_to(“John”) Hello John setup( name = 'Hello world app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
  • 5. Static type declarations Cython can compile pure python code. To improve performance, use cdef add static type declarations # test1.pyx, 35% speedup def f(x): return x**2-x def integrate_f(a, b, N): s=0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s*dx # 4 time speedup over python version def f(double x): return x**2-x def integrate_f(double a, double b, int N): cdef int i cdef double s, dx s=0 dx = (b-a)/N for i in range(N): s += f(a+i*dx) return s*dx
  • 6. Typing function #declare c-style function 150 times speedup cdef double f(double x) except ? -2: return x**2 - x >>> import hello >>> hasattr(hello,'f') False # if use cpdef instead of cdef, a Python wrapper is also created annotation tell you why your code take time $ cython.py -a hello.pyx a html (hello.html) is created, Click the yellow, you will get why the Python API is called here
  • 7. Calling C function A complete list of these cimport file see LibsitepackagesCythonIncludes from libc.math cimport sin cdef double f(double x): return sin(x*x) If Cython do not provide read-to-use declaration, access C code by cdef # instruct Cython generate C code that include math.h header file # C compiler will see it at compile time cdef extern from “math.h”: double sin(double) cdef double f(double x): return sin(x*x)
  • 8. Using C libraries Step 1: redefine .pxd head file Step 2: create a pyx define Queue class in Python # file: cqueue.pxd # copy most part of C head file here cdef extern from "libcalg/queue.h": ctypedef struct Queue: pass ctypedef void* QueueValue Queue* queue_new() void queue_free(Queue* queue) # file: queue.pyx cimport cqueue cdef class Queue: cdef cqueue.Queue *_c_queue def __cinit__(self): self._c_queue = cqueue.queue_new()
  • 9. Using C libraries - cont or step 3.2: include the lib in step 3.1: change the setup.py the option $ CFLAGS="change I/usr/local/otherdir/calg/include" ext_modules = [Extension("queue LDFLAGS="", ["queue.pyx"])] L/usr/local/otherdir/calg/lib" python setup.py build_ext -i to ext_modules = [ Extension("queu e", ["queue.pyx"], libraries=["calg"]) ] calg lib see Simon Howard, C Algorithms library, http://c-algorithms.sourceforge.net/
  • 10. Using C++ in Cython • Brief overview of C++ support in Cython(Cython v0.13) – C++ objects can now be dynamically allocated with new and del keywords. – C++ objects can be stack-allocated. – C++ classes can be declared with the new keyword cppclass. – Templated classes are supported. – Overloaded functions are supported. – Overloading of C++ operators (such as operator+, operator[],...) is supported.
  • 11. Review of this Slides 1. introduce the Cython 2. How to install Cython 3. An example show how to compile a Cython project 4. Optimize the pure Python code with Cython 5. Call C function in Python code 6. Use C library in Python code