Skip to content

Instantly share code, notes, and snippets.

@beniwohli
Last active February 17, 2016 20:10
Show Gist options
  • Save beniwohli/acc2bee28a9c0f029488 to your computer and use it in GitHub Desktop.
Save beniwohli/acc2bee28a9c0f029488 to your computer and use it in GitHub Desktop.
Timer decorator / context manager
import time
import functools
class timer(object):
"""
Usage
As decorator:
@timer()
def my_function():
# do something
As context manager
def my_function():
with timer('doing something'):
# do something
"""
def __init__(self, name=None):
self.name = name
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
print '%s: %.3fs' % (self.name, self.interval)
def __call__(self, func):
self.name = self.name or func.__name__
@functools.wraps(func)
def decorated(*args, **kwds):
with self:
return func(*args, **kwds)
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment