我尝试编写一个函数,它将运行传递给它的另一个函数,并返回它的执行时间。
有人能给我解释一下为什么下面的总是打印0.0秒吗?
import time
def run_and_return_execution_time(func):
t_start = time.time()
func
return time.time() - t_start
t_execution = run_and_return_execution_time(func)
print('Execution time: ',t_execution)
我正在尝试计时的函数确实正在执行,如果我使用以下方法,它将打印大约44秒:
t_start = time.time()
func()
t_end = time.time()
print('Execution time: ',t_end - t_start)
我知道还有其他的方法来实现这一点,比如使用cProfile,但是我很有兴趣了解一下这里发生了什么。
应该在传递的函数中添加偏执词。 否则将不执行该函数。 您的代码应该如下所示:
import time
def run_and_return_execution_time(func):
t_start = time.time()
# Added the parantheses to the function:
func()
return time.time() - t_start
t_execution = run_and_return_execution_time(func)
print('Execution time: ',t_execution)
您忘记了将()
放在第5行对func
的调用之后,因此它实际上并没有运行该函数。
下面的代码显示了修复程序:
import time
def run_and_return_execution_time(func):
t_start = time.time()
func() # ------------ Here is the change ----------------
return time.time() - t_start
t_execution = run_and_return_execution_time(func)
print('Execution time: ', t_execution)