Skip to content

Instantly share code, notes, and snippets.

@mesaglio
Created January 30, 2021 15:23
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 mesaglio/dec7ccbc812d5edaeaf75c7d127f4920 to your computer and use it in GitHub Desktop.
Save mesaglio/dec7ccbc812d5edaeaf75c7d127f4920 to your computer and use it in GitHub Desktop.
profile decorator cProfile - Python 3.9
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