Skip to content

Instantly share code, notes, and snippets.

@melvinkcx
Last active December 23, 2019 05:53
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 melvinkcx/8a545215a7bc49c0739d35ad5056cabb to your computer and use it in GitHub Desktop.
Save melvinkcx/8a545215a7bc49c0739d35ad5056cabb to your computer and use it in GitHub Desktop.
A decorator to run profiler in Python
"""
with Python 3.8, you can use context manager with cProfile.Profile()
"""
def profile(func, filename="stats"):
def wrapper(*args, **kwargs):
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
v = func(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
with open(filename, 'a') as f:
f.write(s.getvalue())
return v
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment