python uses decorator to record method time-consuming

Ideas

Python uses a decorator to record the time consumption of a method. The purpose is that every time a method is executed, the time consumption of the method can be recorded, without the need to create a temporary variable before and after the execution of each method to record the time consumption.

Method 1 (not recommended):

Before and after the execution of each method, create a temporary variable to record the time consumption. The code is as follows. The disadvantage is that if there are 10 or 100 methods, then it must not be written 10 or 100 times? And if you write it like this, it’s easy to miss something and it’s too redundant.

def fun():
	# 开始计时
    start_time = time.time()
	# 模拟耗时
    time.sleep(2)
    
    # 停止计时
    end_time = time.time()
    print("fun01执行喽")

Method 2 (recommended):

The advantage of using a decorator to record time-consuming is that marking it before the method that needs to be recorded is equivalent to passing this method to another method. Let method A execute method B (commonly known as: nesting doll ).
The advantage of this is that we only need to make annotations and do not need to change the content of time-consuming methods that need to be recorded. This can reduce errors and redundancy. The code is as follows:

import time
# 使用装饰器,记录方法执行耗时
def timer(method_name):
    def decorator(func):
        def wrapper(*args, **kwargs):
            # 开始计时
            start_time = time.time()

            # 执行方法
            result = func(*args, **kwargs)

            # 停止计时
            end_time = time.time()

            # 统计耗时并输出
            execution_time = end_time - start_time
            log = "{} 执行耗时: {:.2f} 秒".format(method_name, execution_time)
            print(log)
            return result

        return wrapper

    return decorator

# 方法1 使用装饰器标注
@timer("fun01()")
def fun01():
	# 模拟耗时
    time.sleep(2)
    print("fun01执行喽")

# 方法2 不使用任何标注
def fun02():
	# 模拟耗时
	time.sleep(1)
    print("fun02执行喽")

# 方法3 使用装饰器标注
@timer("fun03()")
def fun03():
	# 模拟耗时
    time.sleep(3)
    print("fun03执行喽")


# 顺序执行fun01、02和03
fun01()
fun02()
fun03()

The code is executed directly, and you can see the following output:
1. It outputs fun01() "executing", but the output takes 2.01 seconds, because it sleeps for 2 seconds and uses a decorator.
2. Fun02() "executing" is output, but the execution time is not recorded. The reason is that the "decorator" is not used to record the time of the method.
3. Fun03() outputs "execution", but the output time is 3.00 seconds, because it sleeps for 3 seconds and uses a decorator.
Insert image description here

Organizing is not easy!

like! Pay attention!

Guess you like

Origin blog.csdn.net/qq_40600379/article/details/132262733