SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Cython
Close to the metal Python
Kyiv.py #10
Taras Lyapun
Python is a wonderful language that
allows us to solve problems quickly and
elegantly, but...
...but nothing ideal in this world. As a
interpreted, dynamical language without
static typization, Python is slow.
How many times have you heard or said,
"We can always rewrite bottlenecks on
C"?
How can we do this?
- By hand using Python C API
- SWIG
- Boost.Python
- ctypes
- SIP, Py++, f2py, PyD, Interrogate, Robin, ...
- Cython
Cython
- Programming language based on Python
- The source code gets translated into
optimized C/C++ code and compiled as Python
extension modules
- Originally based on the well-known Pyrex
- This code is executed within the CPython
runtime environment, but at the speed of
compiled C and with the ability to call directly
into C libraries.
Install
pip install cython
Building with a distutils
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("hello", ["hello.pyx"])]
setup(
name = 'Hello world app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
python setup.py build_ext --inplace
Building with pyximport
import pyximport
pyximport.install()
Building manually
cython path/to/your.pyx
gcc ...
Workflow
- Python code
- Profiling
- Unittests
- Cython code
Original
mv util.py util.pyx
x2 performance
cython -a util.pyx
Just add static typization
ncalls tottime percall cumtime percall filename:lineno(function)
8 0.010 0.001 0.010 0.001 {qrcode.util.lost_point}
x16 performance.
Easy achieve 100-1000x!
cython -a util.pyx
Overview
- Almost like Python (with few exceptions)
- top-level classes and functions
- loops, with, try-except/finally...
- lambda
- generators
- import
- Py3 support
Type declaration
- cdef - for static typization
cdef double dx, s
- cdef - as a C function
cdef double f(double x):
return sin(x**2)
- cdef class - extensions
cdef class MyType:
cdef int field
- cpdef - C function + Python wrapper
Classes
cdef class MyClass(SomeClass):
- "builtin" extension type
- single inheritance, only from other extension
types
- fixed, typed fields
- C-only access by default, or readonly/public
- Python + C methods
Pure python mode
@cython.ccall
@cython.returns(cython.double)
@cython.locals(x=cython.double, y=cython.
double)
def float_mult(x, y):
return x * y
Pure python mode
# test.py
def float_mult(x, y):
return x * y
# test.pxd
cpdef double float_mult(double x, double y)
(but no access to C functions)
Exceptions
cdef double f(double x) except -1:
cdef double f(double x) except? -1:
cdef int spam() except *:
cdef int spam() except +:
Exceptions
File "run.py", line 9, in <module>
"""
File "qrcode/main.py", line 7, in make
return qr.make_image()
File "qrcode/main.py", line 169, in make_image
self.make()
File "qrcode/main.py", line 53, in make
self.best_fit(start=self.version)
File "qrcode/main.py", line 108, in best_fit
self.error_correction, self.data_list)
File "util.pyx", line 401, in qrcode.util.create_data (qrcode/util.c:7844)
File "util.pyx", line 418, in qrcode.util.create_data (qrcode/util.c:7513)
qrcode.util.DataOverflowError: Code length overflow. Data size (916) > size
available (128)
Profiling
# cython: profile=True
@cython.profile(False)
cython -X profile=True ...
Also
- debugging with GDB
- Easy wrap C/C++ libraries
- Numpy, cmath, etc
- with nogil - release GIL
- cython.parallel - for native parallelism (OpenMP)
- and a lot of other cool hackers things
Thanks!
http://cython.org/

Weitere ähnliche Inhalte

Was ist angesagt?

All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
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
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 

Was ist angesagt? (20)

C++ via C#
C++ via C#C++ via C#
C++ via C#
 
COSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in JuliaCOSCUP: Foreign Function Call in Julia
COSCUP: Foreign Function Call in Julia
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
 
Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11
 
D vs OWKN Language at LLnagoya
D vs OWKN Language at LLnagoyaD vs OWKN Language at LLnagoya
D vs OWKN Language at LLnagoya
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Writing a Python C extension
Writing a Python C extensionWriting a Python C extension
Writing a Python C extension
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
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)
 
C
CC
C
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Extending Python - EuroPython 2014
Extending Python - EuroPython 2014Extending Python - EuroPython 2014
Extending Python - EuroPython 2014
 
Files
FilesFiles
Files
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 

Ähnlich wie Cython - close to metal Python

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

Ähnlich wie Cython - close to metal Python (20)

PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
 
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
 
Python Bindings Overview
Python Bindings OverviewPython Bindings Overview
Python Bindings Overview
 
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
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 
mpi4py.pdf
mpi4py.pdfmpi4py.pdf
mpi4py.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...
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Porting To Symbian
Porting To SymbianPorting To Symbian
Porting To Symbian
 
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...
 
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
 
Introduction to Python.Net
Introduction to Python.NetIntroduction to Python.Net
Introduction to Python.Net
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
 
Pysense: wireless sensor computing in Python?
Pysense: wireless sensor computing in Python?Pysense: wireless sensor computing in Python?
Pysense: wireless sensor computing in Python?
 
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
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Cython - close to metal Python

  • 1. Cython Close to the metal Python Kyiv.py #10 Taras Lyapun
  • 2. Python is a wonderful language that allows us to solve problems quickly and elegantly, but...
  • 3. ...but nothing ideal in this world. As a interpreted, dynamical language without static typization, Python is slow.
  • 4. How many times have you heard or said, "We can always rewrite bottlenecks on C"?
  • 5. How can we do this? - By hand using Python C API - SWIG - Boost.Python - ctypes - SIP, Py++, f2py, PyD, Interrogate, Robin, ... - Cython
  • 6. Cython - Programming language based on Python - The source code gets translated into optimized C/C++ code and compiled as Python extension modules - Originally based on the well-known Pyrex - This code is executed within the CPython runtime environment, but at the speed of compiled C and with the ability to call directly into C libraries.
  • 8. Building with a distutils from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension("hello", ["hello.pyx"])] setup( name = 'Hello world app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules ) python setup.py build_ext --inplace
  • 9. Building with pyximport import pyximport pyximport.install()
  • 11. Workflow - Python code - Profiling - Unittests - Cython code
  • 13. mv util.py util.pyx x2 performance
  • 15. Just add static typization ncalls tottime percall cumtime percall filename:lineno(function) 8 0.010 0.001 0.010 0.001 {qrcode.util.lost_point} x16 performance. Easy achieve 100-1000x!
  • 17. Overview - Almost like Python (with few exceptions) - top-level classes and functions - loops, with, try-except/finally... - lambda - generators - import - Py3 support
  • 18. Type declaration - cdef - for static typization cdef double dx, s - cdef - as a C function cdef double f(double x): return sin(x**2) - cdef class - extensions cdef class MyType: cdef int field - cpdef - C function + Python wrapper
  • 19. Classes cdef class MyClass(SomeClass): - "builtin" extension type - single inheritance, only from other extension types - fixed, typed fields - C-only access by default, or readonly/public - Python + C methods
  • 21. Pure python mode # test.py def float_mult(x, y): return x * y # test.pxd cpdef double float_mult(double x, double y) (but no access to C functions)
  • 22. Exceptions cdef double f(double x) except -1: cdef double f(double x) except? -1: cdef int spam() except *: cdef int spam() except +:
  • 23. Exceptions File "run.py", line 9, in <module> """ File "qrcode/main.py", line 7, in make return qr.make_image() File "qrcode/main.py", line 169, in make_image self.make() File "qrcode/main.py", line 53, in make self.best_fit(start=self.version) File "qrcode/main.py", line 108, in best_fit self.error_correction, self.data_list) File "util.pyx", line 401, in qrcode.util.create_data (qrcode/util.c:7844) File "util.pyx", line 418, in qrcode.util.create_data (qrcode/util.c:7513) qrcode.util.DataOverflowError: Code length overflow. Data size (916) > size available (128)
  • 25. Also - debugging with GDB - Easy wrap C/C++ libraries - Numpy, cmath, etc - with nogil - release GIL - cython.parallel - for native parallelism (OpenMP) - and a lot of other cool hackers things