python检测函数运行时间用【巧用装饰器】

众所周知,python中的time模块可以获取时间戳,然后得到程序片运行所消耗的时间。但靠时间戳相减得到运行时间对于大规模程序是比较卑微的,你得命名很多个变量名去记录时间戳。这个时候,可以利用装饰器来记录时间。

本文介绍两种方法,进行对比。

常规版:

from time import time

def run():
    res = 0
    for i in range(10000):
        for j in range(10000):
            res += 1
            res -= 1


if __name__ == '__main__':
    start = time() # 获取函数开始的时间戳
    run()
    end = time() # 获取函数结束的时间戳
    print('time cost:', end-start) # 相减得到运行时间

decorator版:

from time import time
 
 
def time_costing(func):
    def core():
        start = time()
        func()
        print('time costing:', time() - start)
    return core
 
 
@time_costing
def run():
    res = 0
    for i in range(10000):
        for j in range(10000):
            res += 1
            res -= 1
 
 
if __name__ == '__main__':
    run()

用装饰器测函数时间的优越性体现在,只需在任何函数前一行加@xxx就可以。实属帅气又方便,对于大规模程序的细节时间监测非常有用。干净又卫生。

装饰器不太明白的同学请戳《python中的装饰器

hope it's useful to you, thanks.

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/106651069