SlideShare a Scribd company logo
1 of 26
Download to read offline
What I Know About
Python Performance
A. Jesse Jiryu Davis

http://emptysqua.re

MongoDB
Agenda

• Single-threaded
• Multi-threaded
• Gevent
Single-Threaded
Why is Python slow?




• Everything’s an object

• Lookup
Everything’s an object
def f():!
i = 2000!
i += 1!
Everything’s an object

import dis!
dis.dis(f)!
Everything’s an object
def f():!
i = 2000!
i += 1
0
3
6
9
12
13

LOAD_CONST
STORE_FAST
LOAD_FAST
LOAD_CONST
INPLACE_ADD!
STORE_FAST

1
0
0
2

(2000)!
(i)!
(i)!
(1)!

0 (i)!
Everything’s an object
def f():!
i = 2000!
i += 1

malloc!
0
3
6
9
12
13

LOAD_CONST
STORE_FAST
LOAD_FAST
LOAD_CONST
INPLACE_ADD!
STORE_FAST

1
0
0
2

(2000)!
(i)!
malloc!
(i)!
(1)!

0 (i)!
Everything’s an object
12 seconds for 100M numbers:
total = 0!
for i in longs:!
total += i!
print float(total) / len(longs)
Everything’s an object
1 second for 100M numbers:

print float(sum(longs)) / len(longs)
Everything’s an object
0.2 seconds for 100M numbers:

print numpy.mean(array)
Lookup
n = 1!
!

def f():!
print n!
n = 1!
!

def f():!
print n!

0 LOAD_GLOBAL
3 PRINT_ITEM!
4 PRINT_NEWLINE
hashtable lookup

0 (n)!
n = 1!
!

def f(n=n):!
print n!

0 LOAD_FAST
3 PRINT_ITEM!
4 PRINT_NEWLINE
array offset

0 (n)!
Profiling
Profiling
import yappi!
!

yappi.start(builtins=True)!
my_function()!
yappi.stop()!
stats = yappi.get_func_stats()!
stats.save('yappi.callgrind', type='callgrind')!
KCacheGrind
KCacheGrind
Multi-threaded
Multi-threaded
When is the GIL released?




• Every 100 bytecodes

• Acquiring other locks

• Network or file operations
Multi-threaded
Because:
Py_BEGIN_ALLOW_THREADS!
outlen = recv(s->sock_fd, cbuf, len);!
Py_END_ALLOW_THREADS!

socketmodule.c
Multi-threaded
Because:
Py_BEGIN_ALLOW_THREADS!
outlen = recv(s->sock_fd, cbuf, len);!
Py_END_ALLOW_THREADS!

release the GIL!

socketmodule.c
Multi-threaded
This makes sense:
threads = [!
threading.Thread(target=download_a_url())!
for _ in range(10)]!
!

for t in threads:!
t.start()!
!

for t in threads:!
t.join()!
Multi-threaded
This makes no sense:
threads = [!
threading.Thread(target=do_calculations())!
for _ in range(10)]!
!

for t in threads:!
t.start()!
!

for t in threads:!
t.join()!
Gevent
from gevent import monkey!
monkey.patch_all()!
!

threads = [!
threading.Thread(target=download_a_url())]!
!

for t in threads:!
t.start()!
!

for t in threads:!
t.join()!

actually a greenlet
GreenletProfiler
Links

http://bit.ly/pythonperformance

More Related Content

Viewers also liked

파이썬 스터디 15장
파이썬 스터디 15장파이썬 스터디 15장
파이썬 스터디 15장
SeongHyun Ahn
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
Gavin Roy
 
Red teaming the CCDC
Red teaming the CCDCRed teaming the CCDC
Red teaming the CCDC
scriptjunkie
 
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
Olga Kochetova
 
When you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the massesWhen you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the masses
Michele Orru
 
Selenium을 이용한 동적 사이트 크롤러 만들기
Selenium을 이용한 동적 사이트 크롤러 만들기Selenium을 이용한 동적 사이트 크롤러 만들기
Selenium을 이용한 동적 사이트 크롤러 만들기
Gyuhyeon Jeon
 

Viewers also liked (20)

Profiling - 실시간 대화식 프로파일러
Profiling - 실시간 대화식 프로파일러Profiling - 실시간 대화식 프로파일러
Profiling - 실시간 대화식 프로파일러
 
파이썬 스터디 15장
파이썬 스터디 15장파이썬 스터디 15장
파이썬 스터디 15장
 
Deep into your applications, performance & profiling
Deep into your applications, performance & profilingDeep into your applications, performance & profiling
Deep into your applications, performance & profiling
 
Smashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profilingSmashing the bottleneck: Qt application profiling
Smashing the bottleneck: Qt application profiling
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
Modern Post-Exploitation Strategies - 44CON 2012
Modern Post-Exploitation Strategies - 44CON 2012Modern Post-Exploitation Strategies - 44CON 2012
Modern Post-Exploitation Strategies - 44CON 2012
 
Red teaming the CCDC
Red teaming the CCDCRed teaming the CCDC
Red teaming the CCDC
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
 
DEFCON 22: Bypass firewalls, application white lists, secure remote desktops ...
DEFCON 22: Bypass firewalls, application white lists, secure remote desktops ...DEFCON 22: Bypass firewalls, application white lists, secure remote desktops ...
DEFCON 22: Bypass firewalls, application white lists, secure remote desktops ...
 
Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24Six Degrees of Domain Admin - BloodHound at DEF CON 24
Six Degrees of Domain Admin - BloodHound at DEF CON 24
 
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
Hack your ATM with friend's Raspberry.Py (Black Hat EU-2014)
 
When you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the massesWhen you don't have 0days: client-side exploitation for the masses
When you don't have 0days: client-side exploitation for the masses
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Introduction to Apache Accumulo
Introduction to Apache AccumuloIntroduction to Apache Accumulo
Introduction to Apache Accumulo
 
[1D2]아이비컨과 공유기 해킹을 통한 인도어 IOT 삽질기
[1D2]아이비컨과 공유기 해킹을 통한 인도어 IOT 삽질기[1D2]아이비컨과 공유기 해킹을 통한 인도어 IOT 삽질기
[1D2]아이비컨과 공유기 해킹을 통한 인도어 IOT 삽질기
 
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
 
[1A1]행복한프로그래머를위한철학
[1A1]행복한프로그래머를위한철학[1A1]행복한프로그래머를위한철학
[1A1]행복한프로그래머를위한철학
 
Selenium을 이용한 동적 사이트 크롤러 만들기
Selenium을 이용한 동적 사이트 크롤러 만들기Selenium을 이용한 동적 사이트 크롤러 만들기
Selenium을 이용한 동적 사이트 크롤러 만들기
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 

Similar to Python Performance: Single-threaded, multi-threaded, and Gevent

Creating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUICreating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUI
Gonzalo Cordero
 

Similar to Python Performance: Single-threaded, multi-threaded, and Gevent (9)

Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
Persistent Data Structures - partial::Conf
Persistent Data Structures - partial::ConfPersistent Data Structures - partial::Conf
Persistent Data Structures - partial::Conf
 
From render() to DOM
From render() to DOMFrom render() to DOM
From render() to DOM
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
System insight without Interference
System insight without InterferenceSystem insight without Interference
System insight without Interference
 
Long Live the Rubyist
Long Live the RubyistLong Live the Rubyist
Long Live the Rubyist
 
ClojureScript Introduction
ClojureScript IntroductionClojureScript Introduction
ClojureScript Introduction
 
Creating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUICreating Hybrid mobile apps with YUI
Creating Hybrid mobile apps with YUI
 

More from emptysquare

More from emptysquare (6)

Cat-Herd's Crook
Cat-Herd's CrookCat-Herd's Crook
Cat-Herd's Crook
 
MongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep DiveMongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep Dive
 
What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 

Recently uploaded

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
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
 
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
 
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 Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Python Performance: Single-threaded, multi-threaded, and Gevent