计算代码运行时间--带有返回值的装饰器

示例代码

import time


def cal_time(fn):
    """计算程序运行时间的函数"""
    def inner():
        start_time = time.time()
        ret = fn()
        end_time = time.time()
        print("程序一共执行了%s" % (end_time - start_time) + '')
        return ret
    return inner


@cal_time
def func():
    """带有返回值的求阶乘的函数"""
    x = 1
    for i in range(1, 100000):
        x *= i
    print(x)
    return x


result = func()  # 相当于 func = cal_time(func)
print(result) # 查看inner函数的返回值
View Code

运行结果:

 

posted @ 2021-04-02 18:57  御姐玫瑰  阅读(35)  评论(0编辑  收藏  举报
levels of contents