Last active
December 23, 2019 05:53
-
-
Save melvinkcx/8a545215a7bc49c0739d35ad5056cabb to your computer and use it in GitHub Desktop.
A decorator to run profiler 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
""" | |
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