Skip to content

Instantly share code, notes, and snippets.

@jiffyclub
Last active February 8, 2021 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiffyclub/5191024 to your computer and use it in GitHub Desktop.
Save jiffyclub/5191024 to your computer and use it in GitHub Desktop.
Magics for starting Snakeviz from IPython. Use %snakeviz and %%snakeviz in place of %prun and %%prun to profile a block of code and launch a Snakeviz view of the profile.
import subprocess
import tempfile
import time
from IPython.core.magic import register_line_cell_magic
def snakeviz(line, cell=None):
"""
Profile code and display the profile in Snakeviz.
Works as a line or cell magic.
"""
# get location for saved profile
filename = tempfile.NamedTemporaryFile().name
# call signature for prun
line = '-q -D ' + filename + ' ' + line
# generate the stats file using IPython's prun magic
ip = get_ipython()
if cell:
ip.run_cell_magic('prun', line, cell)
else:
ip.run_line_magic('prun', line)
# start up a Snakeviz server
sv = subprocess.Popen(['snakeviz', filename])
# give time for the Snakeviz page to load then shut down the server
time.sleep(20)
sv.terminate()
def load_ipython_extension(ipython):
ipython.register_magic_function(snakeviz, magic_kind='line_cell')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment