Skip to content

Instantly share code, notes, and snippets.

@thoward
Created January 29, 2017 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoward/e616dedf822741653db3b252d65a4e6e to your computer and use it in GitHub Desktop.
Save thoward/e616dedf822741653db3b252d65a4e6e to your computer and use it in GitHub Desktop.
Some snippets for profiling in Python
# paste these in
import contextlib
@contextlib.contextmanager
def profile(result_file_name=None):
import cProfile
import pstats
import sys
pr = cProfile.Profile()
pr.enable()
try:
yield
finally:
pr.disable()
ps = pstats.Stats(pr, stream=sys.stdout)
ps.sort_stats('cumulative')
if result_file_name:
ps.dump_stats(result_file_name)
else:
ps.print_stats()
# in code
with profile('profiling.stats'):
ret = something(blah)
# view output with snakeviz
# https://jiffyclub.github.io/snakeviz/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment