在 2020 iMac 27" 上的 MacOS 13.4.1 上运行 python 3.9。 在尝试使用装饰器来计时函数的执行时间时,我发现正在计时的函数返回的值减少为“无”。 timing_decorator 是从一个被遗忘的源复制的。它适用于不返回值的函数。
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:7.3f} seconds to run.")
return
return wrapper
@timing_decorator
def funky(p1,p2):
return p1 * p2
print(funky(6,7))
按原样运行此代码将打印“None”。 注释掉“@timing_decorator”行会打印预期结果“42” 我发现了很多关于将参数传递给装饰函数的参考资料,但没有关于返回值的参考资料。
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:7.3f} seconds to run.")
return result # Return the actual result of the normal function instead of nothing
return wrapper
@timing_decorator
def funky(p1,p2):
return p1 * p2
print(funky(6,7))