Skip to content

Instantly share code, notes, and snippets.

@jdelafon
Created July 21, 2017 13:52
Show Gist options
  • Save jdelafon/4e392f889a757972410a14301a0e9543 to your computer and use it in GitHub Desktop.
Save jdelafon/4e392f889a757972410a14301a0e9543 to your computer and use it in GitHub Desktop.
Python timers
def timer(function):
""" A decorator that makes the decorated *function* return its execution time."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
t1 = time.time()
result = function(*args, **kwargs)
t2 = time.time()
print(" @time '{}': {:.4f} s.".format(str(function), t2-t1))
return result
return wrapper
class Timer(object):
"""Use as a context manager:
with Timer() as t:
<block>
"""
def __init__(self, verbose=True):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs # millisecs
if self.verbose:
print("@Timer: {:.5f} s".format(self.msecs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment