gpt4 book ai didi

python - 计时函数并获取返回值

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:18 24 4
gpt4 key购买 nike

我知道我可以用这个

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

计算 hello 函数以参数 100 运行需要多长时间。但是假设我的 hello 函数返回字符串 'world' 并且我想存储返回的值 and 也必须花费时间执行。

可以吗?

最佳答案

如果您只想对特定函数的特定调用计时,您可以执行以下操作。这将为您提供一次运行的确切时间。但是,您可能只想使用 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)

关于python - 计时函数并获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com