利用装饰器计算函数运行的时间

时间:2022-07-23
本文章向大家介绍利用装饰器计算函数运行的时间,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import time
from functools import wraps
def time_this_function(func):
    #作为装饰器使用,返回函数执行需要花费的时间
    @wraps(func)
    def wrapper(*args,**kwargs):
        start=time.time()
        result=func(*args,**kwargs)
        end=time.time()
        print("函数:",func.__name__,"运行时间:",round(end-start,4),"s")
        return result
    return wrapper
if __name__=='__main__':
    @time_this_function
    def count_number(n):
        while n>0:
            time.sleep(0.1)
            n+=-1
    count_number(10)
输出:函数: count_number 运行时间: 1.0036 s