SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?Kuniyasu Suzaki
 
LAS16-TR06: Remoteproc & rpmsg development
LAS16-TR06: Remoteproc & rpmsg developmentLAS16-TR06: Remoteproc & rpmsg development
LAS16-TR06: Remoteproc & rpmsg developmentLinaro
 
Wiresharkの解析プラグインを作る ssmjp 201409
Wiresharkの解析プラグインを作る ssmjp 201409Wiresharkの解析プラグインを作る ssmjp 201409
Wiresharkの解析プラグインを作る ssmjp 201409稔 小林
 
Qt5 (minimal) on beaglebone, with Yocto
Qt5 (minimal) on beaglebone, with YoctoQt5 (minimal) on beaglebone, with Yocto
Qt5 (minimal) on beaglebone, with YoctoPrabindh Sundareson
 
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)NGINX, Inc.
 
C#でもメタプログラミングがしたい!!
C#でもメタプログラミングがしたい!!C#でもメタプログラミングがしたい!!
C#でもメタプログラミングがしたい!!TATSUYA HAYAMIZU
 
Pci express transaction
Pci express transactionPci express transaction
Pci express transactiony38y38
 
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月VirtualTech Japan Inc.
 
Python パッケージの影響を歴史から理解してみよう!
Python パッケージの影響を歴史から理解してみよう!Python パッケージの影響を歴史から理解してみよう!
Python パッケージの影響を歴史から理解してみよう!Kir Chou
 
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法de:code 2017
 
PSR-1 と PSR-2 を 5分でざっくり理解する
PSR-1 と PSR-2 を5分でざっくり理解するPSR-1 と PSR-2 を5分でざっくり理解する
PSR-1 と PSR-2 を 5分でざっくり理解するWataru Terada
 
データサイエンスワールドからC++を眺めてみる
データサイエンスワールドからC++を眺めてみるデータサイエンスワールドからC++を眺めてみる
データサイエンスワールドからC++を眺めてみるShintaro Fukushima
 
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
『例えば、PHPを避ける』以降PHPはどれだけ安全になったかHiroshi Tokumaru
 
Jenkins 2.0 Pipeline & Blue Ocean
Jenkins 2.0 Pipeline & Blue OceanJenkins 2.0 Pipeline & Blue Ocean
Jenkins 2.0 Pipeline & Blue OceanAkihiko Horiuchi
 
QtとC++でGUIプログラミング
QtとC++でGUIプログラミングQtとC++でGUIプログラミング
QtとC++でGUIプログラミングseanchas_t
 

Mais procurados (20)

TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
TEE (Trusted Execution Environment)は第二の仮想化技術になるか?
 
Docker, LinuX Container
Docker, LinuX ContainerDocker, LinuX Container
Docker, LinuX Container
 
LAS16-TR06: Remoteproc & rpmsg development
LAS16-TR06: Remoteproc & rpmsg developmentLAS16-TR06: Remoteproc & rpmsg development
LAS16-TR06: Remoteproc & rpmsg development
 
Scale Kubernetes to support 50000 services
Scale Kubernetes to support 50000 servicesScale Kubernetes to support 50000 services
Scale Kubernetes to support 50000 services
 
Qt5 on ti processors
Qt5 on ti processorsQt5 on ti processors
Qt5 on ti processors
 
Wiresharkの解析プラグインを作る ssmjp 201409
Wiresharkの解析プラグインを作る ssmjp 201409Wiresharkの解析プラグインを作る ssmjp 201409
Wiresharkの解析プラグインを作る ssmjp 201409
 
Qt5 (minimal) on beaglebone, with Yocto
Qt5 (minimal) on beaglebone, with YoctoQt5 (minimal) on beaglebone, with Yocto
Qt5 (minimal) on beaglebone, with Yocto
 
Jenkins-CI
Jenkins-CIJenkins-CI
Jenkins-CI
 
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)
「これからはじめるNGINX技術解説~基本編」セミナー (NGINX Back to Basic in JP)
 
C#でもメタプログラミングがしたい!!
C#でもメタプログラミングがしたい!!C#でもメタプログラミングがしたい!!
C#でもメタプログラミングがしたい!!
 
Pci express transaction
Pci express transactionPci express transaction
Pci express transaction
 
qmake入門
qmake入門qmake入門
qmake入門
 
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月
GPU Container as a Serviceを実現するための最新OSS徹底比較 - OpenStack最新情報セミナー 2017年7月
 
Python パッケージの影響を歴史から理解してみよう!
Python パッケージの影響を歴史から理解してみよう!Python パッケージの影響を歴史から理解してみよう!
Python パッケージの影響を歴史から理解してみよう!
 
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法
[DI08] その情報うまく取り出せていますか? ~ 意外と簡単、Azure Search で短時間で検索精度と利便性を向上させるための方法
 
PSR-1 と PSR-2 を 5分でざっくり理解する
PSR-1 と PSR-2 を5分でざっくり理解するPSR-1 と PSR-2 を5分でざっくり理解する
PSR-1 と PSR-2 を 5分でざっくり理解する
 
データサイエンスワールドからC++を眺めてみる
データサイエンスワールドからC++を眺めてみるデータサイエンスワールドからC++を眺めてみる
データサイエンスワールドからC++を眺めてみる
 
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
『例えば、PHPを避ける』以降PHPはどれだけ安全になったか
 
Jenkins 2.0 Pipeline & Blue Ocean
Jenkins 2.0 Pipeline & Blue OceanJenkins 2.0 Pipeline & Blue Ocean
Jenkins 2.0 Pipeline & Blue Ocean
 
QtとC++でGUIプログラミング
QtとC++でGUIプログラミングQtとC++でGUIプログラミング
QtとC++でGUIプログラミング
 

Semelhante a 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
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfAnassElHousni
 

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

Mais 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
 

Mais 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
 

Último

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
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
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
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)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

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