装饰器

练习
请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:

# -*- coding: utf-8 -*-
import time, functools

def metric(fn):
    @functools.wraps(fn)
    def wrapper(*args,**kwargs):
        t1=time.time()
        run=fn(*args, **kwargs)
        t2=time.time()
        print('%s executed in %s ms' % (fn.__name__,t2-t1))
        return run
    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('测试失败!')
elif s != 7986:
    print('测试失败!')

  

posted @ 2018-04-29 17:14  Gringer  阅读(172)  评论(0编辑  收藏  举报