Skip to content

Instantly share code, notes, and snippets.

@felixbr
Last active September 25, 2016 09:49
Show Gist options
  • Save felixbr/071fee55058b87e060af to your computer and use it in GitHub Desktop.
Save felixbr/071fee55058b87e060af to your computer and use it in GitHub Desktop.
from __future__ import print_function, absolute_import, unicode_literals
from contextlib import contextmanager
from time import time
from io import StringIO
import cProfile
import pstats
@contextmanager
def runtime_logging(task_name, logger=None):
t_start = time()
yield
t_stop = time()
t_elapsed = t_stop - t_start
result = 'Took {1:4.3f}s for task: "{0}"'.format(task_name, t_elapsed)
if logger:
logger.debug(result)
else:
print(result)
@contextmanager
def runtime_profiling(task_name, logger=None):
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
# some in-memory file voodoo
s = StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('tottime')
ps.print_stats()
if logger:
logger.debug(s.getvalue())
else:
print(s.getvalue())
@felixbr
Copy link
Author

felixbr commented Dec 17, 2015

usage:

from runtime_profiling import *

with runtime_logging("thing i want to do"):
     # do something you want to profile or call a function here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment