請設計一個decorator烁试,它可作用于任何函數上,并打印該函數的執(zhí)行時間:
代碼:
import functools,time
def metric(func):
def wrapper(*args, **kw):
print('%s executed in %s ms' % (func.__name__, func))
return func(*args, **kw)
return wrapper
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y;
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z;
f = fast(11, 22)
s = slow(11, 22, 33)
if f !=33:
print('fail!')
elif s !=7986:
print('fail!')