Python的装饰器可以做一些类似Java SpringBoot AOP切面注解的事情。
# 无参数decorator
import time
def performance(f):
def fn(*args, **kw):
start = time.time()
print 'function start'
r = f(*args, **kw)
print 'function finish'
end = time.time()
print 'call %s() in %fs' % (f.__name__, (end - start))
return r
return fn
@performance
def factorial(n):
print 'factorial'
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
输出:
function start
factorial
function finish
call factorial() in 0.005252s
3628800
# 有参数decorator
import time
def performance(unit):
def perf_decorator(f):
def wrapper(*args, **kw):
t1 = time.time()
r = f(*args, **kw)
t2 = time.time()
t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
print 'call %s() in %f %s' % (f.__name__, t, unit)
return r
return wrapper
return perf_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
输出:
call factorial() in 4.901886 ms
3628800