SlideShare a Scribd company logo
1 of 21
Download to read offline
LET’S BUILD A PYTHON
PROFILER IN 25 LOC!
by Noam Elfanbaum
Navigate : Space / Arrow Keys | - Menu | - Fullscreen | - Overview | - Blackout | - Speaker | - HelpM F O B S ?

1 / 21
ABOUT ME
Data Engineering lead at Bluevine
Help organise &
Find me online at &
PywebIL Pycon Israel
@noamelf noamelf.com
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

2 / 21
WHAT IS A PROGRAM PROFILE?
A pro le is a set of statistics that
describes how often and for how long
various parts of the program executed.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

3 / 21
PYTHON’S (STDLIB) PROFILERS
Python has 2 builtin pro lers in stdlib:
pro le - an early pure Python implementation
cPro le - a C extended pro ler for better
performance
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

4 / 21
Pro ling demo
# profiling_demo.py
def super_power(x):
return x ** x ** x
def count_digits(num):
return len(str(num))
result = super_power(7)
digit_count = count_digits(result)
print(f'Num of digits: {digit_count}')
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

5 / 21
Optimized demo
# optimized_demo.py
import math
def super_power(x):
return x ** x ** x
def count_digits(num):
return int(math.log10(num)) + 1
result = super_power(7)
digit_count = count_digits(result)
print(digit_count)
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

6 / 21
IT'S MAGIC! RIGHT?
When inside a Python program you have pretty easy
access to its stack.
Most pro lers run as part of your Python process.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

7 / 21
Accessing the process call stack
# stack_access.py
import sys
import traceback
def show_stack():
for _, call_stack in sys._current_frames().items():
for frame in traceback.extract_stack(call_stack):
print(f'{frame.filename}:{frame.lineno}:'
f'{frame.name} - "{frame.line}"')
def bar():
show_stack()
bar()
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

8 / 21
TYPES OF TRIGGERS -> TYPE OF PROFILES
There are two types of pro lers that differ upon their
triggers:
Deterministic pro lers - triggered on function/line
called (like pro le/cPro le)
Statistical pro lers - triggered on a time interval
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

9 / 21
HOW DO DETERMINISTIC PROFILERS
WORK?
Python let you specify a callback that gets run when
interpreter events happen:
sys.setprofile - triggered when a function or
a line of code is called
sys.settrace - triggered only when a function
is called
When the callback gets called, it records the stack
for later analysis.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

10 / 21
Using setpro le
# setprofile.py
import sys
import traceback
def profiler(call_stack, event, arg):
line = traceback.extract_stack(call_stack)[0]
print(f'event: {event} | arg: {arg} | line: {line.line}')
sys.setprofile(profiler)
print('Hello world!')
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

11 / 21
HOW DO STATISTICAL PROFILERS WORK?
Statistical pro lers sample the program on a given
interval.
One way to implement the sampling is to ask the OS
kernel to interrupt the program on a given interval.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

12 / 21
Using OS signals to trigger sampling
# statistical_sampling.py
import atexit, signal, traceback
def print_handler(signum, call_stack):
line = traceback.extract_stack(call_stack)[0]
print(f'line: {line.line} (signum={signum})')
def start(handler, interval=1):
signal.signal(signal.SIGPROF, handler)
signal.setitimer(signal.ITIMER_PROF, interval, interval)
atexit.register(lambda: signal.setitimer(
signal.ITIMER_PROF, 0))
start(print_handler)
result = 7 ** 7 ** 7
print(len(str(result)))
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

13 / 21
WHEN TO USE WHICH PROFILER?
Statistical pro lers:
Low, controllable and predicted overhead is
possible by optimizing the sampling interval
Less accurate result since it, by design, misses
function/line calls.
More suitable for continuous, low impact
production monitoring.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

14 / 21
Deterministic pro lers:
Introduces a xed amount of latency for every
function call / line of code executed.
Collects the exact program execution stack
More suitable for interactive/local debugging.
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

15 / 21
NOW, LET’S BUILD A
(NAIVE) STATISTICAL
PROFILER IN 25 LOC!
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

16 / 21
Statistical Flame graph Pro ler
import atexit
import collections
import signal
import traceback
stats = collections.defaultdict(int)
def _sample(_, call_stack):
stack = traceback.extract_stack(call_stack)
formatted_stack = ';'.join(line.line for line in stack)
stats[formatted_stack] += 1
def start(interval=0.005):
signal signal(signal SIGPROF sample)
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

17 / 21
Simple usage of sfPro ler
import sfProfiler
def calc(x):
return x ** x
def main():
calc(100_000)
calc(200_000)
sfProfiler.start()
main()
print(sfProfiler.format_stats())
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

18 / 21
A more complex example
import sys
import tempfile
import urllib.request
import sfProfiler
def save_pep(pep):
url = f'https://www.python.org/dev/peps/pep-{pep:04}'
with urllib.request.urlopen(url) as request:
html = request.read()
with tempfile.TemporaryFile('wb') as f:
f.write(html)
def main():
for pep in range(4):
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

19 / 21
REFERENCE
Brendan Gregg's tool
Juila Evans about Ruby and Python pro lers
Nylas performance where they explain how
they built a homemade performance monitoring
service (recommended!).
Python's
This talk can be found on
Flame Graph
post
post
pro lers docs
Github
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

20 / 21
Thanks!
[ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]

21 / 21

More Related Content

What's hot (20)

Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
MPHS RC Design Flow
MPHS RC Design FlowMPHS RC Design Flow
MPHS RC Design Flow
 
XREST Protocol
XREST ProtocolXREST Protocol
XREST Protocol
 
Programming in c (importance of c)
Programming in c (importance of c)Programming in c (importance of c)
Programming in c (importance of c)
 
Lesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th stepLesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th step
 
C++ Events
C++ EventsC++ Events
C++ Events
 
Lesson 3.1 variables and constant
Lesson 3.1 variables and constantLesson 3.1 variables and constant
Lesson 3.1 variables and constant
 
3DD 1e Laura
3DD 1e Laura3DD 1e Laura
3DD 1e Laura
 
4Developers 2015: Clean JavaScript code - only dream or reality - Sebastian Ł...
4Developers 2015: Clean JavaScript code - only dream or reality - Sebastian Ł...4Developers 2015: Clean JavaScript code - only dream or reality - Sebastian Ł...
4Developers 2015: Clean JavaScript code - only dream or reality - Sebastian Ł...
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Lesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving processLesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving process
 
GCC compiler
GCC compilerGCC compiler
GCC compiler
 
Al2ed chapter17
Al2ed chapter17Al2ed chapter17
Al2ed chapter17
 
Gccgdb
GccgdbGccgdb
Gccgdb
 
Lesson 5 .1 selection structure
Lesson 5 .1 selection structureLesson 5 .1 selection structure
Lesson 5 .1 selection structure
 
Code optimisation presnted
Code optimisation presntedCode optimisation presnted
Code optimisation presnted
 
Optimization
OptimizationOptimization
Optimization
 
LTO plugin
LTO pluginLTO plugin
LTO plugin
 
From System Modeling to Automated System Testing
From System Modeling to Automated System TestingFrom System Modeling to Automated System Testing
From System Modeling to Automated System Testing
 

Similar to Let’s Build a Python Profiler in 25 LOC

1 Vampir Overview
1 Vampir Overview1 Vampir Overview
1 Vampir OverviewPTIHPA
 
eBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureeBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureNetronome
 
Princeton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance ToolingPrinceton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance ToolingHenry Schreiner
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Henry Schreiner
 
RHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfRHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfHarsh Shah
 
Preparing to program Aurora at Exascale - Early experiences and future direct...
Preparing to program Aurora at Exascale - Early experiences and future direct...Preparing to program Aurora at Exascale - Early experiences and future direct...
Preparing to program Aurora at Exascale - Early experiences and future direct...inside-BigData.com
 
Squeezing Blood From a Stone V1.2
Squeezing Blood From a Stone V1.2Squeezing Blood From a Stone V1.2
Squeezing Blood From a Stone V1.2Jen Costillo
 
Track A-Compilation guiding and adjusting - IBM
Track A-Compilation guiding and adjusting - IBMTrack A-Compilation guiding and adjusting - IBM
Track A-Compilation guiding and adjusting - IBMchiportal
 
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...GetInData
 
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetes
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetesSpryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetes
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetesBernd Alter
 
LIFT: A Legacy InFormation retrieval Tool
LIFT: A Legacy InFormation retrieval ToolLIFT: A Legacy InFormation retrieval Tool
LIFT: A Legacy InFormation retrieval ToolKellyton Brito
 
Cray XT Porting, Scaling, and Optimization Best Practices
Cray XT Porting, Scaling, and Optimization Best PracticesCray XT Porting, Scaling, and Optimization Best Practices
Cray XT Porting, Scaling, and Optimization Best PracticesJeff Larkin
 
使用 Prometheus 監控 Kubernetes Cluster
使用 Prometheus 監控 Kubernetes Cluster 使用 Prometheus 監控 Kubernetes Cluster
使用 Prometheus 監控 Kubernetes Cluster inwin stack
 
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdam
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, AmsterdamFelix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdam
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdamcamunda services GmbH
 
Probe Debugging
Probe DebuggingProbe Debugging
Probe DebuggingESUG
 
Conf42 Python_ ML Enhanced Event Streaming Apps with Python Microservices
Conf42 Python_ ML Enhanced Event Streaming Apps with Python MicroservicesConf42 Python_ ML Enhanced Event Streaming Apps with Python Microservices
Conf42 Python_ ML Enhanced Event Streaming Apps with Python MicroservicesTimothy Spann
 
Digital design with Systemc
Digital design with SystemcDigital design with Systemc
Digital design with SystemcMarc Engels
 
May2010 hex-core-opt
May2010 hex-core-optMay2010 hex-core-opt
May2010 hex-core-optJeff Larkin
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019corehard_by
 

Similar to Let’s Build a Python Profiler in 25 LOC (20)

1 Vampir Overview
1 Vampir Overview1 Vampir Overview
1 Vampir Overview
 
eBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging InfrastructureeBPF Tooling and Debugging Infrastructure
eBPF Tooling and Debugging Infrastructure
 
Princeton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance ToolingPrinceton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance Tooling
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
 
RHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfRHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdf
 
Preparing to program Aurora at Exascale - Early experiences and future direct...
Preparing to program Aurora at Exascale - Early experiences and future direct...Preparing to program Aurora at Exascale - Early experiences and future direct...
Preparing to program Aurora at Exascale - Early experiences and future direct...
 
Squeezing Blood From a Stone V1.2
Squeezing Blood From a Stone V1.2Squeezing Blood From a Stone V1.2
Squeezing Blood From a Stone V1.2
 
Track A-Compilation guiding and adjusting - IBM
Track A-Compilation guiding and adjusting - IBMTrack A-Compilation guiding and adjusting - IBM
Track A-Compilation guiding and adjusting - IBM
 
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...
Functioning incessantly of Data Science Platform with Kubeflow - Albert Lewan...
 
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetes
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetesSpryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetes
Spryker meetup-distribute-your-spryker-deployment-with-docker-and-kubernetes
 
LIFT: A Legacy InFormation retrieval Tool
LIFT: A Legacy InFormation retrieval ToolLIFT: A Legacy InFormation retrieval Tool
LIFT: A Legacy InFormation retrieval Tool
 
Cray XT Porting, Scaling, and Optimization Best Practices
Cray XT Porting, Scaling, and Optimization Best PracticesCray XT Porting, Scaling, and Optimization Best Practices
Cray XT Porting, Scaling, and Optimization Best Practices
 
使用 Prometheus 監控 Kubernetes Cluster
使用 Prometheus 監控 Kubernetes Cluster 使用 Prometheus 監控 Kubernetes Cluster
使用 Prometheus 監控 Kubernetes Cluster
 
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdam
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, AmsterdamFelix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdam
Felix Müller: Live Coding: Zeebe - Camunda Days Oslo, CPH, Amsterdam
 
Probe Debugging
Probe DebuggingProbe Debugging
Probe Debugging
 
Conf42 Python_ ML Enhanced Event Streaming Apps with Python Microservices
Conf42 Python_ ML Enhanced Event Streaming Apps with Python MicroservicesConf42 Python_ ML Enhanced Event Streaming Apps with Python Microservices
Conf42 Python_ ML Enhanced Event Streaming Apps with Python Microservices
 
Digital design with Systemc
Digital design with SystemcDigital design with Systemc
Digital design with Systemc
 
Optimizing Your CI Pipelines
Optimizing Your CI PipelinesOptimizing Your CI Pipelines
Optimizing Your CI Pipelines
 
May2010 hex-core-opt
May2010 hex-core-optMay2010 hex-core-opt
May2010 hex-core-opt
 
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
The Hitchhiker's Guide to Faster Builds. Viktor Kirilov. CoreHard Spring 2019
 

Recently uploaded

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 

Let’s Build a Python Profiler in 25 LOC

  • 1. LET’S BUILD A PYTHON PROFILER IN 25 LOC! by Noam Elfanbaum Navigate : Space / Arrow Keys | - Menu | - Fullscreen | - Overview | - Blackout | - Speaker | - HelpM F O B S ?  1 / 21
  • 2. ABOUT ME Data Engineering lead at Bluevine Help organise & Find me online at & PywebIL Pycon Israel @noamelf noamelf.com [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  2 / 21
  • 3. WHAT IS A PROGRAM PROFILE? A pro le is a set of statistics that describes how often and for how long various parts of the program executed. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  3 / 21
  • 4. PYTHON’S (STDLIB) PROFILERS Python has 2 builtin pro lers in stdlib: pro le - an early pure Python implementation cPro le - a C extended pro ler for better performance [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  4 / 21
  • 5. Pro ling demo # profiling_demo.py def super_power(x): return x ** x ** x def count_digits(num): return len(str(num)) result = super_power(7) digit_count = count_digits(result) print(f'Num of digits: {digit_count}') [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  5 / 21
  • 6. Optimized demo # optimized_demo.py import math def super_power(x): return x ** x ** x def count_digits(num): return int(math.log10(num)) + 1 result = super_power(7) digit_count = count_digits(result) print(digit_count) [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  6 / 21
  • 7. IT'S MAGIC! RIGHT? When inside a Python program you have pretty easy access to its stack. Most pro lers run as part of your Python process. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  7 / 21
  • 8. Accessing the process call stack # stack_access.py import sys import traceback def show_stack(): for _, call_stack in sys._current_frames().items(): for frame in traceback.extract_stack(call_stack): print(f'{frame.filename}:{frame.lineno}:' f'{frame.name} - "{frame.line}"') def bar(): show_stack() bar() [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  8 / 21
  • 9. TYPES OF TRIGGERS -> TYPE OF PROFILES There are two types of pro lers that differ upon their triggers: Deterministic pro lers - triggered on function/line called (like pro le/cPro le) Statistical pro lers - triggered on a time interval [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  9 / 21
  • 10. HOW DO DETERMINISTIC PROFILERS WORK? Python let you specify a callback that gets run when interpreter events happen: sys.setprofile - triggered when a function or a line of code is called sys.settrace - triggered only when a function is called When the callback gets called, it records the stack for later analysis. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  10 / 21
  • 11. Using setpro le # setprofile.py import sys import traceback def profiler(call_stack, event, arg): line = traceback.extract_stack(call_stack)[0] print(f'event: {event} | arg: {arg} | line: {line.line}') sys.setprofile(profiler) print('Hello world!') [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  11 / 21
  • 12. HOW DO STATISTICAL PROFILERS WORK? Statistical pro lers sample the program on a given interval. One way to implement the sampling is to ask the OS kernel to interrupt the program on a given interval. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  12 / 21
  • 13. Using OS signals to trigger sampling # statistical_sampling.py import atexit, signal, traceback def print_handler(signum, call_stack): line = traceback.extract_stack(call_stack)[0] print(f'line: {line.line} (signum={signum})') def start(handler, interval=1): signal.signal(signal.SIGPROF, handler) signal.setitimer(signal.ITIMER_PROF, interval, interval) atexit.register(lambda: signal.setitimer( signal.ITIMER_PROF, 0)) start(print_handler) result = 7 ** 7 ** 7 print(len(str(result))) [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  13 / 21
  • 14. WHEN TO USE WHICH PROFILER? Statistical pro lers: Low, controllable and predicted overhead is possible by optimizing the sampling interval Less accurate result since it, by design, misses function/line calls. More suitable for continuous, low impact production monitoring. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  14 / 21
  • 15. Deterministic pro lers: Introduces a xed amount of latency for every function call / line of code executed. Collects the exact program execution stack More suitable for interactive/local debugging. [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  15 / 21
  • 16. NOW, LET’S BUILD A (NAIVE) STATISTICAL PROFILER IN 25 LOC! [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  16 / 21
  • 17. Statistical Flame graph Pro ler import atexit import collections import signal import traceback stats = collections.defaultdict(int) def _sample(_, call_stack): stack = traceback.extract_stack(call_stack) formatted_stack = ';'.join(line.line for line in stack) stats[formatted_stack] += 1 def start(interval=0.005): signal signal(signal SIGPROF sample) [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  17 / 21
  • 18. Simple usage of sfPro ler import sfProfiler def calc(x): return x ** x def main(): calc(100_000) calc(200_000) sfProfiler.start() main() print(sfProfiler.format_stats()) [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  18 / 21
  • 19. A more complex example import sys import tempfile import urllib.request import sfProfiler def save_pep(pep): url = f'https://www.python.org/dev/peps/pep-{pep:04}' with urllib.request.urlopen(url) as request: html = request.read() with tempfile.TemporaryFile('wb') as f: f.write(html) def main(): for pep in range(4): [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  19 / 21
  • 20. REFERENCE Brendan Gregg's tool Juila Evans about Ruby and Python pro lers Nylas performance where they explain how they built a homemade performance monitoring service (recommended!). Python's This talk can be found on Flame Graph post post pro lers docs Github [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  20 / 21
  • 21. Thanks! [ GitPitch @ github/noamelf/Lets-build-a-Python-profiler-in-25-LOC ]  21 / 21