Skip to content

Instantly share code, notes, and snippets.

@QuantumGhost
Last active February 6, 2017 03:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save QuantumGhost/57c702e9a47e5692011526acfd295c05 to your computer and use it in GitHub Desktop.
Save QuantumGhost/57c702e9a47e5692011526acfd295c05 to your computer and use it in GitHub Desktop.
A simple decorator for profiling python function.
import cProfile
import functools
import pstats
from cStringIO import StringIO
def profile(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
print('===== begin profile =====')
pr = cProfile.Profile()
pr.enable()
res = func(*args, **kwargs)
pr.disable()
sio = StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=sio).sort_stats(sortby)
ps.print_stats()
print(sio.getvalue())
print('===== end profile =====')
return res
return wrapped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment