【问题标题】:Time a function and get the returned value计时函数并获取返回值
【发布时间】:2014-10-12 17:11:27
【问题描述】:

我知道我可以用这个

from timeit import timeit
test = lambda f: timeit(lambda:f(100), number=1)
t1 = test(hello)

计算hello 函数使用参数100 运行所需的时间。但是假设我的hello 函数返回字符串'world',我想存储该返回值并且还需要执行时间。

可以吗?

【问题讨论】:

  • 你想在这里实现什么?如果您正在设置number=1timeit 可能不是适合您的工具。
  • @jonrsharpe 我想计算运行一次hello(100) 需要多长时间。这种方法是我从中得到的帖子的最佳答案。您能建议您使用哪种其他方法吗?我不明白反对票...
  • 你将如何处理返回值?如果您只是想确保它符合您的期望,请考虑 assert
  • @jonrsharpe 对于我的实验室,我的讲师要求我们在实际运行期间为所有函数计时。这不仅仅是为了检查性能。我需要为我的函数计时并将其结果用作程序中后续函数的参数。
  • 你可能想要这样的东西 - stackoverflow.com/questions/582336/… - 投票结束你的问题作为重复

标签: python performance time


【解决方案1】:

如果您只想为特定函数的特定调用计时,可以执行以下操作。这将为您提供一次跑步的确切时间。但是,您可能只想使用 timeit 或 profile 来更准确地了解您的程序正在做什么。这些工具汇总多次运行以获得更准确的平均案例结果。

创建一个函数,调用一个函数,记录时间,然后运行函数并返回值和时间增量。

import time

def timed(func, *args, **kwargs):
    start = time.time()
    out = func(*args, **kwargs)
    return out, time.time() - start

def my_func(value):
    time.sleep(value)
    return value

print(timed(my_func(5)))  # (5, 5.0050437450408936)

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2016-01-03
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多