【问题标题】:Function using time.time() to return execution time of another passed function always returns 0.0 (Python)使用 time.time() 返回另一个传递函数的执行时间的函数总是返回 0.0 (Python)
【发布时间】:2020-07-03 14:33:42
【问题描述】:

我尝试编写一个函数,该函数将运行另一个传递给它的函数,并返回其执行时间。

有人可以向我解释为什么以下总是打印 0.0 秒吗?

为了澄清,我定义中的“func”是调用 func 而无需添加括号。在调用 run_and_return_execution_time(func) 时,我看到了来自 func 的打印分析输出。我目前正在 Jupyter 笔记本中运行它 - 不确定这是否有任何区别。

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,但我有兴趣了解这里发生了什么。

【问题讨论】:

  • 将括号添加到您的run_and_return_execution_time#...; func();
  • 我会把它添加为问题的答案

标签: python time parameter-passing


【解决方案1】:

您应该为您传递的函数添加括号。否则该函数将不会被执行。您的代码应如下所示:

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)

【讨论】:

  • 感谢您的回复,我意识到我犯了两个错误。在我的示例代码中,我写了调用 run_and_return_execution_time(func),但实际上我在执行 run_and_return_execution_time(func())。一旦我将括号添加到定义中的 func() 并调用 run_and_return_execution_time(func),时间就会按预期返回。奇怪的是,我把它们弄混了,func 实际上是在运行,但不是在计时。无论如何,感谢您的解决方案
  • run_and_return_execution_time(func()) 会先执行函数,然后将结果传递给计时函数
【解决方案2】:

你忘记把()放在第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)

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 2010-09-15
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多