Skip to content

Instantly share code, notes, and snippets.

@romuloceccon
Last active April 12, 2018 11:08
Show Gist options
  • Save romuloceccon/99fa3afa94c824ffd7ca731dd8c8a0d8 to your computer and use it in GitHub Desktop.
Save romuloceccon/99fa3afa94c824ffd7ca731dd8c8a0d8 to your computer and use it in GitHub Desktop.
Quick functions to easily profile Python code
import monotonic
from time import clock as cpu_time
import cProfile, pstats
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def time_it(label):
start_total = monotonic.monotonic()
start_cpu = cpu_time()
def split(name=None):
diff_total = monotonic.monotonic() - start_total
diff_cpu = cpu_time() - start_cpu
desc = '%s (%s)' % (label, name) if name else label
print('%s: %f (%f)' % (desc, diff_total, diff_cpu))
return split
def profile():
pr = cProfile.Profile()
pr.enable()
def stop_profile():
pr.disable()
s = StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return stop_profile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment