Last active
August 29, 2015 14:18
-
-
Save 1337/a14c2702c0120c862ab2 to your computer and use it in GitHub Desktop.
Python function/block timer
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
from __future__ import print_function | |
from functools import wraps | |
from time import time | |
__all__ = ['timer'] | |
def timer(msg=None): | |
def is_callable(thing): | |
return getattr(thing, '__call__', None) | |
class Timer(object): | |
msg = '' | |
func = None | |
before = None | |
def __init__(self, func=None, msg=''): | |
self.func = func | |
self.msg = msg | |
def __call__(self, *args, **kwargs): | |
if self.func: | |
return self._runner(self.func, args, kwargs, msg=self.msg) | |
elif not kwargs and len(args) == 1 and is_callable(args[0]): | |
func = args[0] | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
return self._runner(func, args, kwargs, msg=self.msg) | |
return wrapped | |
def __enter__(self): | |
self.before = time() | |
def __exit__(self, *args): | |
self.after = time() | |
self._log(self.msg, self.after - self.before) | |
@classmethod | |
def _runner(cls, func, args, kwargs, msg=''): | |
before = time() | |
res = func(*args, **kwargs) | |
after = time() | |
cls._log(msg, after - before) | |
return res | |
@staticmethod | |
def _log(msg, time): | |
print('%s %f' % (msg, time)) | |
# with timer(): | |
if msg is None: | |
return Timer() | |
# @timer | |
elif is_callable(msg): | |
return wraps(msg)(Timer(func=msg)) | |
# @timer('notes') | |
return Timer(msg=msg) | |
if __name__ == '__main__': | |
@timer | |
def foo(): pass | |
foo() | |
@timer('decorator with comments') | |
def baz(): pass | |
baz() | |
with timer('with statement with comments'): | |
with timer(): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment