gpt4 book ai didi

python - 在 python 中有效地对不同输入(不同大小)的函数进行基准测试

转载 作者:行者123 更新时间:2023-11-28 20:10:12 28 4
gpt4 key购买 nike

我正在尝试对具有不同大小的不同输入的函数进行基准测试。

例如,我有一个函数 something(array),它将一个可变长度的 numpy 数组作为输入和一个可能的参数列表 args = [np.random.rand(3 , 2, i) for i in range(1,1000)].我现在想做的是根据输入测试 something 需要的时间。

我目前所做的是:

def iterator(ys):

times = []
for i in range(len(ys)):
start = timer()
test = something(ys[i])
end = timer()
times.append(end - start)

return times

有了这个我就得到了我想要的结果。问题是使用这种方法我没有得到任何关键数据,例如每个输入大小的方差或均值。我还可以执行第二个循环,在该循环中多次运行 iterator 并使用结果计算关键值,但如果有的话,我宁愿使用已建立的方法。

我尝试应用 pytest-benchmark ( https://pytest-benchmark.readthedocs.io/en/stable/ ) 但无法找到将参数列表传递给函数的方法。

也许你们中的一些人对此有很好的解决方案!

最佳答案

最方便的方法是使用 Ipython line magic %timeit 或 cell magic %%timeit 执行计时测量。我通常定义要测试的输入数据大小并在循环中运行它:

def list_search(lst, item):
for el in lst:
if el == item:
return True
return False

for n in (100, 1000, 10000, 100000):
data = list(range(n))
%timeit list_search(data, data[-1])

%timeit 函数采用多个参数来修改其行为:

%timeit [-n -r [-t|-c] -q -p<P> -o] statement

Options: -n: execute the given statement times in a loop. If is not provided, is determined so as to get sufficient accuracy.

-r: number of repeats , each consisting of loops, and take the best result. Default: 7

(来自https://ipython.readthedocs.io/en/stable/interactive/magics.html)

关于python - 在 python 中有效地对不同输入(不同大小)的函数进行基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59306904/

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