SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019
MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019
MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019Grid Dynamics
 
How to Choose a Software Update Mechanism for Embedded Linux Devices
How to Choose a Software Update Mechanism for Embedded Linux DevicesHow to Choose a Software Update Mechanism for Embedded Linux Devices
How to Choose a Software Update Mechanism for Embedded Linux DevicesLeon Anavi
 
OPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialOPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialDalton Valadares
 
20150511 jun lee_openstack neutron 분석 (최종)
20150511 jun lee_openstack neutron 분석 (최종)20150511 jun lee_openstack neutron 분석 (최종)
20150511 jun lee_openstack neutron 분석 (최종)rootfs32
 
Lcu14 107- op-tee on ar mv8
Lcu14 107- op-tee on ar mv8Lcu14 107- op-tee on ar mv8
Lcu14 107- op-tee on ar mv8Linaro
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programmingsudhir singh yadav
 
How VXLAN works on Linux
How VXLAN works on LinuxHow VXLAN works on Linux
How VXLAN works on LinuxEtsuji Nakai
 
Negociacion de codecs en asterisk
Negociacion de codecs en asteriskNegociacion de codecs en asterisk
Negociacion de codecs en asteriskPaloSanto Solutions
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machineAlexei Starovoitov
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a prosparkfabrik
 
وهذا يوضح الشغل بالشركه
وهذا  يوضح الشغل بالشركهوهذا  يوضح الشغل بالشركه
وهذا يوضح الشغل بالشركهfprevermaji
 
Cours cisco icnd1
Cours cisco icnd1Cours cisco icnd1
Cours cisco icnd1saqrjareh
 
Ntp cheat sheet
Ntp cheat sheetNtp cheat sheet
Ntp cheat sheetcsystemltd
 
LCU14-103: How to create and run Trusted Applications on OP-TEE
LCU14-103: How to create and run Trusted Applications on OP-TEELCU14-103: How to create and run Trusted Applications on OP-TEE
LCU14-103: How to create and run Trusted Applications on OP-TEELinaro
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLinaro
 

Tendances (20)

MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019
MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019
MPL: modular pipeline library - Dynamic Talks Milwaukee 4/11/2019
 
How to Choose a Software Update Mechanism for Embedded Linux Devices
How to Choose a Software Update Mechanism for Embedded Linux DevicesHow to Choose a Software Update Mechanism for Embedded Linux Devices
How to Choose a Software Update Mechanism for Embedded Linux Devices
 
OPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build TutorialOPTEE on QEMU - Build Tutorial
OPTEE on QEMU - Build Tutorial
 
20150511 jun lee_openstack neutron 분석 (최종)
20150511 jun lee_openstack neutron 분석 (최종)20150511 jun lee_openstack neutron 분석 (최종)
20150511 jun lee_openstack neutron 분석 (최종)
 
Lcu14 107- op-tee on ar mv8
Lcu14 107- op-tee on ar mv8Lcu14 107- op-tee on ar mv8
Lcu14 107- op-tee on ar mv8
 
Complete Guide for Linux shell programming
Complete Guide for Linux shell programmingComplete Guide for Linux shell programming
Complete Guide for Linux shell programming
 
How VXLAN works on Linux
How VXLAN works on LinuxHow VXLAN works on Linux
How VXLAN works on Linux
 
Negociacion de codecs en asterisk
Negociacion de codecs en asteriskNegociacion de codecs en asterisk
Negociacion de codecs en asterisk
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
Twilio
TwilioTwilio
Twilio
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machine
 
SERIALES
SERIALES SERIALES
SERIALES
 
WebRTC on Mobile
WebRTC on MobileWebRTC on Mobile
WebRTC on Mobile
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a pro
 
وهذا يوضح الشغل بالشركه
وهذا  يوضح الشغل بالشركهوهذا  يوضح الشغل بالشركه
وهذا يوضح الشغل بالشركه
 
Cours cisco icnd1
Cours cisco icnd1Cours cisco icnd1
Cours cisco icnd1
 
Ntp cheat sheet
Ntp cheat sheetNtp cheat sheet
Ntp cheat sheet
 
Managing APIs with MuleSoft
Managing APIs with MuleSoftManaging APIs with MuleSoft
Managing APIs with MuleSoft
 
LCU14-103: How to create and run Trusted Applications on OP-TEE
LCU14-103: How to create and run Trusted Applications on OP-TEELCU14-103: How to create and run Trusted Applications on OP-TEE
LCU14-103: How to create and run Trusted Applications on OP-TEE
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platform
 

Similaire à Introduction to cython

Writing a Python C extension
Writing a Python C extensionWriting a Python C extension
Writing a Python C extensionSqreen
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal PythonTaras Lyapun
 
An Introduction to CMake
An Introduction to CMakeAn Introduction to CMake
An Introduction to CMakeICS
 
Introduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationIntroduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationKevin Keraudren
 
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 PythonHenry Schreiner
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.NetStefan Schukat
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
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++Uilian Ries
 
Introduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxIntroduction-to-C-Part-1.pptx
Introduction-to-C-Part-1.pptxNEHARAJPUT239591
 
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJIntroduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJ
Introduction-to-C-Part-1 JSAHSHAHSJAHSJAHSJHASJmeharikiros2
 
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.pdfssuser33f16f
 
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...bhargavi804095
 
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...bhargavi804095
 
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 meetingHenry Schreiner
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲Mohammad Reza Kamalifard
 

Similaire à 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
 
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
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
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
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
 

Plus de 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 structuresJohn(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 modulesJohn(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 blocksJohn(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 pythonJohn(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 – algorithmJohn(Qiang) Zhang
 

Plus de 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
 

Dernier

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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