Use python to detect the running time of the function [use the decorator skillfully]

As we all know, the time module in python can get the timestamp, and then get the time consumed by the program piece. However, the running time obtained by subtracting the timestamp is relatively humble for large-scale programs. You have to name many variable names to record the timestamp . At this time, you can use the decorator to record the time.

This article introduces two methods for comparison.

Regular version:

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 version:

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()

The advantage of using decorators to measure function time is that you only need to add @xxx in the line before any function . It is really handsome and convenient, very useful for detailed time monitoring of large-scale programs. Clean and hygienic.

Students who don’t understand the decorator, please poke " Decorator in Python "

hope it's useful to you, thanks.

Guess you like

Origin blog.csdn.net/leviopku/article/details/106651069