【记录】python 计时装饰器 ⏲

实现:

def timer(func):
    def wrapper(*args, **kw):
        tic = time()
        res = func(*args, **kw)
        toc = time()
        print('[timer] {} cost {:.2f}s'.format(func.__name__, toc - tic))
        return res

    return wrapper

[注] 如果 func 函数有返回,wrapper 里也要返回其输出

使用:

@timer
def show(message):
    print(message)

show('hello')

你可能感兴趣的:(【记录】python 计时装饰器 ⏲)