Skip to content

Instantly share code, notes, and snippets.

@joshdover
Last active November 27, 2022 20:38
Show Gist options
  • Save joshdover/1b9c86ef427b1506b7a5dd2509309674 to your computer and use it in GitHub Desktop.
Save joshdover/1b9c86ef427b1506b7a5dd2509309674 to your computer and use it in GitHub Desktop.
Python flamegraphs

Install python-flamegraph into your project:

pip install git+https://github.com/evanhempel/python-flamegraph.git

Record a profile around a bit of code:

import flamegraph
thread = flamegraph.start_profile_thread(fd=open("./profile.log", "w"))

try:
    some_code_to_measure()
finally:
    thread.stop()

Clone the flamegraph SVG generator somewhere:

git clone [email protected]:brendangregg/FlameGraph.git

Generate the SVG:

./flamegraph.pl profile.log > profile.svg

Optionally, checkout the decorator code below

import flamegraph
import os
from functools import wraps
def record_flamegraph(f):
"""
Add to a func to record a flamegraph. Will only keep the graph for most recent time the func was called.
Assumes that the FlameGraph repo is cloned at ../FlameGraph
"""
filename = '{}.{}'.format(f.__module__, f.__name__)
@wraps(f)
def decorator(*args, **kwargs):
fd = open('{}.log'.format(filename), 'w')
profile_thread = flamegraph.start_profile_thread(fd=fd)
try:
return f(*args, **kwargs)
finally:
profile_thread.stop()
fd.close()
os.system('../FlameGraph/flamegraph.pl {0}.log > {0}.svg'.format(filename))
os.system('rm {}.log'.format(filename))
# os.system('open {}.svg'.format(filename))
return decorator
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment