帶有引數的decorator 裝飾器
阿新 • • 發佈:2019-01-22
// 請給 @performace 增加一個引數,允許傳入's'或'ms':
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
import time
def performance(unit):
def a(f):
def b(*args, **kw):
t1 = time.time()
fn = f(*args, **kw)
t2 = time.time()
t = (t2-t1) if unit == 's' else (t2-t1)*1000
print 'call %s() in %s %s' % (f.__name__, t, unit)
return fn
return b
return a
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
- time.time() 獲取當前時間
- t = (t2-t1) if unit == ‘s’ else (t2-t1)*1000
類似 js的三目運算 var t = unit == ‘s’ ? (t2-t1) : (t2-t1)*1000 - fn.__name__ 獲取函式名
- ‘call %s() in %s %s’ % (f._name_, t, unit) %加字母,可對字串傳參