I wrote a decorator that gets the runtime of the program, but the function return value becomes Nonetype.
def gettime(func):
def wrapper(*args, **kw):
t1 = time.time()
func(*args, **kw)
t2 = time.time()
t = (t2-t1)*1000
print("%s run time is: %.5f ms"%(func.__name__, t))
return wrapper
If I don't use the decorator, the return value is correct.
A = np.random.randint(0,100,size=(100, 100))
B = np.random.randint(0,100,size=(100, 100))
def contrast(a, b):
res = np.sum(np.equal(a, b))/(A.size)
return res
res = contrast(A, B)
print("The correct rate is: %f"%res)
The result is:The correct rate is: 0.012400
And if i use the decorator:
@gettime
def contrast(a, b):
res = np.sum(np.equal(a, b))/len(a)
return res
res = contrast(A, B)
print("The correct rate is: %f"%res)
There will report a error:
contrast run time is: 0.00000 ms
TypeError: must be real number, not NoneType
Of course, if I remove the print statement, I can get the correct running time, but the res accepts the Nonetype.
解决方案
Since the wrapper replaces the function decorated, it also needs to pass on the return value:
def wrapper(*args, **kw):
t1 = time.time()
ret = func(*args, **kw) # save it here
t2 = time.time()
t = (t2-t1)*1000
print("%s run time is: %.5f ms"%(func.__name__, t))
return ret # return it here