Last active
February 8, 2021 14:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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