Last active
February 17, 2016 20:10
-
-
Save beniwohli/acc2bee28a9c0f029488 to your computer and use it in GitHub Desktop.
Timer decorator / context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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