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

Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2 BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2 Linaro
 
Generators In Python
Generators In PythonGenerators In Python
Generators In PythonSimplilearn
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginnersRajKumar Rampelli
 
Function-Definition, Need, Declaration, Definition, Arguments, Return Value
Function-Definition, Need, Declaration, Definition, Arguments, Return ValueFunction-Definition, Need, Declaration, Definition, Arguments, Return Value
Function-Definition, Need, Declaration, Definition, Arguments, Return Valuemanish maurya
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaEdureka!
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Olve Maudal
 
twlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsotwlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsoViller Hsiao
 
OOP in C++
OOP in C++OOP in C++
OOP in C++ppd1961
 
Lists and scrollbars
Lists and scrollbarsLists and scrollbars
Lists and scrollbarsmyrajendra
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 

Tendances (20)

C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
 
Function in c program
Function in c programFunction in c program
Function in c program
 
BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2 BUD17-302: LLVM Internals #2
BUD17-302: LLVM Internals #2
 
Gcc porting
Gcc portingGcc porting
Gcc porting
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
Function-Definition, Need, Declaration, Definition, Arguments, Return Value
Function-Definition, Need, Declaration, Definition, Arguments, Return ValueFunction-Definition, Need, Declaration, Definition, Arguments, Return Value
Function-Definition, Need, Declaration, Definition, Arguments, Return Value
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
twlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsotwlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdso
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Lists and scrollbars
Lists and scrollbarsLists and scrollbars
Lists and scrollbars
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 

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
 
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
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfAnassElHousni
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 

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
 
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
 
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 

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

Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceMartin Humpolec
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 

Dernier (20)

Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Things you didn't know you can use in your Salesforce
Things you didn't know you can use in your SalesforceThings you didn't know you can use in your Salesforce
Things you didn't know you can use in your Salesforce
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 

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