编写一个可以打印被装饰函数名称、执行时间、内存地址得装饰器
import time
import functools
from decorator import decorator
> def log1(fn):
def _wrapper(*args, **kwargs):
start = time.clock()
result = fn(*args, **kwargs)
print("%s is invoked with time consumed: %s seconds at address %s" % (fn.__name__, str(time.time() - start), id(fn)))
return result
return _wrapper
@decorator
def log(f, *args, **kwargs):
start = time.time()
result = f(*args, **kwargs)
print("%s is invoked with time consumed: %s at address %s" % (f.__name__, str(time.time() - start), id(f)))
return result
def log2(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
start = time.clock()
result = f(*args, **kwargs)
print("%s is invoked with time consumed: %s seconds at address %s" % (f.__name__, str(time.time() - start), id(f)))
return result
return wrapper
@log2
def f11(x, y):
return x**y
result = f11(2,3)
print("result:" + str(result))
切换到不同的实现中,他们的效果是相同的。
http://www.woaipu.com/shops/zuzhuan/61406
http://www.znds.com/tv-967956-1-1.html
http://www.znds.com/tv-967958-1-1.html
原文:http://www.cnblogs.com/sy646et/p/7197811.html