简体   繁体   English

装饰者的回报与实际回报不同

[英]Decorator's return is different from the actual return

Code代码

Why I am getting different results?为什么我得到不同的结果?

from time import time
def speed_test(func):
    def wrapper(*args, **kwargs):
        start = time()
        func(*args, **kwargs)
        end = time() - start
        print(f"Execution time is: {end:.17f}s  # Decorator")
    return wrapper
@speed_test 
def sorting(L):
    L.sort() # For example
    
def sorting_1(L1):
    L1.sort()
    
T = [10, 5, 3, 1, 0]
L = T.copy()

sorting(T)

a = time()
sorting_1(L)
b = time() - a
print(f"Execution time is: {b:.17f}s  # Main")

Expected output预计 output

Execution time is: 0.00000977516174316s  # Decorator
Execution time is: 0.00000977516174316s  # Main

My output我的 output

Execution time is: 0.00000977516174316s  # Decorator
Execution time is: 0.00000572204589844s  # Main

Why those two results are different?为什么这两个结果不同? Edited: I mean this..编辑:我的意思是这个..

Two things I would say here:在这里我想说两件事:

  1. time.perf_counter is more efficient for things like this time.perf_counter对这样的事情更有效率
  2. [A guess] In python, decorated functions "replace" the original function in the call stack, so they might be slower for that reason. [猜测] 在 python 中,装饰函数“替换”了调用堆栈中的原始 function,因此它们可能因此变慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM