# -*- coding: utf-8 -*- from __future__ import print_function import time import sys from time import strftime import inspect import traceback # http://www.siafoo.net/article/68 # being nice to subsequent decorator calls or chains, otherwise losing the name of the function def timing(result=True, params=True, start=False): def timing_decorator(f): def wrapper(*args, **kw): t1 = time.time() function_result = None try: function_result = f(*args, **kw) return function_result finally: t2 = time.time() from time import strftime strx = strftime("%Y-%m-%d %H:%M:%S") if params and result: if args and kw: strx +=' - % 8.f ms - %s(%r, %r) => %s' % ((t2-t1)*1000.0, f.func_name, str(args), str(kw), str(nprint(function_result))) elif args and not kw: strx +=' - % 8.f ms - %s(%r) => %s' % ((t2-t1)*1000.0, f.func_name, str(args), str(nprint(function_result))) elif not args and kw: strx +=' - % 8.f ms - %s(%r) => %s' % ((t2-t1)*1000.0, f.func_name, str(kw), str(nprint(function_result))) else: strx +=' - % 8.f ms - %s() => %s' % ((t2-t1)*1000.0, f.func_name, str(nprint(function_result))) elif params and not result: if args and kw: strx +=' - % 8.f ms - %s(%r, %r)' % ((t2-t1)*1000.0, f.func_name, str(args), str(kw)) elif args and not kw: strx +=' - % 8.f ms - %s(%r)' % ((t2-t1)*1000.0, f.func_name, str(args)) elif not args and kw: strx +=' - % 8.f ms - %s(%r)' % ((t2-t1)*1000.0, f.func_name, str(kw)) else: strx +=' - % 8.f ms - %s()' % ((t2-t1)*1000.0, f.func_name) elif not params and result: strx +=' - % 8.f ms - %s() => %s' % ((t2-t1)*1000.0, f.func_name, str(nprint(function_result))) else: strx +=' - % 8.f ms - %s()' % ((t2-t1)*1000.0, f.func_name ) if start: d = datetime.fromtimestamp(t1) strx += " start:"+d.strftime("%Y-%m-%d %H:%M:%S") print(strx) wrapper.func_name = f.func_name return wrapper return timing_decorator def nprint(element): from pprint import pprint import sys, StringIO out = StringIO.StringIO() pprint(element,out) return str(out.getvalue()) @timing() def slow_method(): from time import sleep sleep(1) print("Hi I'm a slow method") def main(): slow_method() if __name__ == "__main__": main()
Decorator – References
1. http://www.ellipsix.net/blog/2010/8/more-python-voodoo-optional-argument-decorators.html
2. http://stackoverflow.com/questions/3931627/how-to-build-a-python-decorator-with-optional-parameters/3931903#3931903
3. http://typeandflow.blogspot.com/2011/06/python-decorator-with-optional-keyword.html
4. http://pko.ch/2008/08/22/memoization-in-python-easier-than-what-it-should-be/
5. http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
6. http://wiki.python.org/moin/PythonDecoratorLibrary#Asynchronous_Call
7. http://code.activestate.com/recipes/496879-memoize-decorator-function-with-cache-size-limit/
Leave a Reply