我正在嘗試創建包裝器,它將在此函式的屬性中寫入函式執行時間和呼叫次數。我的代碼適用于簡單的示例函式,但是當我將其應用于 Ackermann 函式時,它停止作業。
我的包裝代碼:
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
func(*args, **kwds)
func.calls = 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return wrapper
阿克曼函式的代碼:
# Test on Ackermann function, code is stolen from SO: https://stackoverflow.com/questions/12678099/ackermann-function-understanding
memo = {}
def naive_ackermann(m, n):
global calll
calll = 0
calll = 1
if not (m, n) in memo:
if m == 0:
print(m, n)
res = n 1
elif n == 0:
print(m, n)
res = naive_ackermann(m - 1, 1)
else:
print(m, n)
res = naive_ackermann(m - 1, naive_ackermann(m, n - 1))
memo[(m, n)] = res
return memo[(m, n)]
print(naive_ackermann(1,1))
沒有包裝它可以正常作業并回傳:
1 1 #
1 0 #
0 1 # <- there are n, m values at each step of execution
0 2 #
3 # <- This is the result of running function
如果我申請profiler:
@profiler
def naive_ackermann(m, n):
....
會有這樣的輸出:
1 1
1 0
0 1
0 None
TypeError: unsupported operand type(s) for : 'NoneType' and 'int'
正如我們所看到n的,None而不是,2我無法理解它為什么會發生。
我很高興得到任何有助于解決此錯誤的建議。謝謝!
uj5u.com熱心網友回復:
您的包裝器不回傳,這與回傳相同None。當您呼叫修飾函式時,實際上您將只運行包裝器。
確保包裝器回傳函式的結果,它會正常作業。
import functools
import time
from functools import wraps
def profiler(func):
@wraps(func)
def wrapper(*args, **kwds):
setattr(func, 'calls', 0)
t1 = time.monotonic() # what's time at the beginning of run
res = func(*args, **kwds)
func.calls = 1 # add 1 to number of calls
t2 = time.monotonic() # what's time at the beginning of run
last_time_taken = t2 - t1
setattr(wrapper, 'last_time_taken', last_time_taken)
setattr(wrapper, 'calls', func.calls)
return res
return wrapper
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/425881.html
上一篇:SQLite3按日期求和
