gpt4 book ai didi

python - timeit 模块 - 获得最快和最慢的循环

转载 作者:行者123 更新时间:2023-11-30 23:04:38 26 4
gpt4 key购买 nike

我想使用 Python 的 timeit 模块进行一些基准测试。有没有办法让 timeit 返回 1000 个循环中最慢和最快循环的时间?

最佳答案

timeit 返回“best of 3”,即有两个参数:一个指定循环中的迭代次数,另一个指定重复循环的次数。传递给 min() 的结果是每个循环的时间,而不是循环的每次迭代的时间。

重复循环的目的是排除同一系统上其他进程的影响 - 来自文档(help('timeit')):

The best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. The -r option is good for this; the default of 3 repetitions is probably enough in most cases.

重复测量 1000 次是没有意义的。您可能打算为单个循环指定 1000 次迭代(默认值为 1000000)。

只有最快的循环(最短时间)才有用——来自help('timeit.Timer.repeat'):

Note: it's tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python's speed, but by other processes interfering with your timing accuracy. So the min() of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics.emphasis is mine

即,最慢的循环表明其他进程对测量的干扰程度。

#!/usr/bin/env python
import timeit

def your_function():
"do something"

t = timeit.Timer(your_function)
# repeat 10 times, 1000000 times through the loop
repeat, number = 10, 1000000
r = t.repeat(repeat, number)
best, worse = min(r), max(r)
print("{number} loops, best of {repeat}: {best:.3g} seconds per loop, "
"worse of {repeat}: {worse:.3g} seconds per loop".format(**vars()))

关于python - timeit 模块 - 获得最快和最慢的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33588041/

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