Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Integralist
Forked from andriykohut/profile_ctx.py
Last active June 7, 2020 15:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/530146ca84f3b899f478b1a309ceaff7 to your computer and use it in GitHub Desktop.
Save Integralist/530146ca84f3b899f478b1a309ceaff7 to your computer and use it in GitHub Desktop.
[Python profiling context management] #python #profiling #performance
import cProfile
import contextlib
import io
import pstats
import sys
import timeit
@contextlib.contextmanager
def prof(*restrictions, stdout=True, dump=None, sortby='cumulative'):
"""Profile code running in this context.
Arguments:
restrictions: Passed down to https://docs.python.org/3.6/library/profile.html#pstats.Stats.print_stats
stdout: write profile stats to stdout
dump: path to dump pstats (optional)
sortby: Sorting criteria: https://docs.python.org/3.6/library/profile.html#pstats.Stats.sort_stats
Usage:
>>> # this will print top 10 calls sorted by 'cumtime' to stdout.
>>> with prof(10, sortby='cumulative'):
>>> do_stuff()
>>> do_other_stuff()
"""
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
if stdout:
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(*restrictions)
print(s.getvalue())
if dump:
pr.dump_stats(dump)
@contextlib.contextmanager
def time_it(name='default_timer', stream=sys.stdout):
start = timeit.default_timer()
yield
stream.write('time_it ({}) - {}\n'.format(name, timeit.default_timer() - start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment