Skip to content

Instantly share code, notes, and snippets.

@whitekid
Last active November 9, 2016 04:28
Show Gist options
  • Select an option

  • Save whitekid/a3501b5252b72c3a7aa37d04eec587e8 to your computer and use it in GitHub Desktop.

Select an option

Save whitekid/a3501b5252b72c3a7aa37d04eec587e8 to your computer and use it in GitHub Desktop.
measure execution time of function or code block
import time
from functools import wraps
class timeit(object):
"""measure execution time and print(or log) it
Args:
printer: message print function
if None, print message to stdout
msg: messsage
Usage:
LOG = logger.getLogger(__name__)
@timeit(LOG.debug)
def foo():
pass
with timeit(LOG.debug, 'a block'):
pass
"""
def __init__(self, printer=None, msg=None):
self.print_func = printer if printer else self.printit
self.msg = msg if msg else ''
self.func = None
@staticmethod
def printit(fmt, *args):
print(fmt % args)
def begin(self):
self.t1 = time.time()
def end(self):
self.print_func("@@@@ %s: %s - %s", self.func, self.msg,
time.time() - self.t1)
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
self.func = func
self.begin()
try:
return func(*args, **kwargs)
finally:
self.end()
self.func = None
return wrapper
def __enter__(self):
self.begin()
def __exit__(self, type, value, traceback):
self.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment