使用装饰器查看函数运行时间

from functools import wraps
import time

def timefn(fn):
    """计算性能的修饰器"""
    @wraps(fn)
    def measure_time(*args, **kwargs):
        t1 = time.perf_counter()
        result = fn(*args, **kwargs)
        t2 = time.perf_counter()
        print(f"{fn.__name__}:{t2 - t1:.2f}s")
        return result

    return measure_time

# 在定义函数前进行装饰
@timefn
def test():
    s = 0
    for i in range(1000000):
        s += 1
    return s


test()

https://blog.csdn.net/ZeropointS/article/details/88815645

posted @ 2022-06-09 14:05  CodeYaSuo  阅读(57)  评论(0编辑  收藏  举报