装饰器的应用
请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
import time,functools def metric(fn): @functools.wraps(fn) def wrapper(*args, **kw): start = time.time() result = fn(*args, **kw) end = time.time() print('%s executed in %s ms' % (fn.__name__, (end - start) * 1000)) return result return wrapper @metric def fast(x,y): time.sleep(0.0012) return x+y @metric def slow(x,y): time.sleep(0.1234) return x*y f = fast(1, 2) s = slow(1, 2) if f != 3: print('Fail') elif s != 2: print('Fail')