簡體   English   中英

裝飾者的回報與實際回報不同

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

代碼

為什么我得到不同的結果?

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

預計 output

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

我的 output

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

為什么這兩個結果不同? 編輯:我的意思是這個..

在這里我想說兩件事:

  1. time.perf_counter對這樣的事情更有效率
  2. [猜測] 在 python 中,裝飾函數“替換”了調用堆棧中的原始 function,因此它們可能因此變慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM