Created
January 29, 2017 20:42
-
-
Save thoward/e616dedf822741653db3b252d65a4e6e to your computer and use it in GitHub Desktop.
Some snippets for profiling in Python
This file contains 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
# 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