Skip to content

Instantly share code, notes, and snippets.

@berlotto
Created April 6, 2021 21:04
Show Gist options
  • Save berlotto/d4ba6b60703a82838e71d6181ed4d6e0 to your computer and use it in GitHub Desktop.
Save berlotto/d4ba6b60703a82838e71d6181ed4d6e0 to your computer and use it in GitHub Desktop.
How to profile functions with decorators
import cProfile
import pstats
import io
def profile(fnc):
def inner(*arg, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc(*arg, **kwargs)
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