Created
January 30, 2021 15:23
-
-
Save mesaglio/dec7ccbc812d5edaeaf75c7d127f4920 to your computer and use it in GitHub Desktop.
profile decorator cProfile - Python 3.9
This file contains hidden or 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
import cProfile, pstats, io | |
def profile(fun): | |
""" | |
print file-function call, number of calls, cumtime, percall(second percall) | |
How to use: | |
@profile | |
def function_to_analize(): | |
... | |
if __name__ == "__main__": | |
function_to_analize() | |
""" | |
def inner(*args, **kargs): | |
pr = cProfile.Profile() | |
pr.enable() | |
retval = fun(*args, **kargs) | |
pr.disable() | |
s = io.StringIO() | |
sortby = 'cumulative' | |
ps = pstats.Stats(pr, stream=s).sort_stats(sortby) | |
ps.print_stats() | |
print(s.getvalue()) | |
return retval | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment