IPython %timeit 选项中的循环和迭代是什么?

IPython %timeit what is loop and iteration in the options?

我想知道 IPython 中的 %timeit 命令

来自docs

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

Options:

-n: execute the given statement times in a loop. If this value is not given, a fitting value is chosen.

-r: repeat the loop iteration times and take the best result. Default: 3

例如,如果我写:

%timeit -n 250 -r 2 [i+1 for i in range(5000)]

那么,-n 250 执行了 [i+1 for i in range(5000)] 250 次?那么-r 2是什么?

它指定重复次数,重复次数用于确定平均值。例如:

%timeit -n 250 a = 2
# 61.9 ns ± 1.01 ns per loop (mean ± std. dev. of 7 runs, 250 loops each)

%timeit -n 250 -r 2 a = 2
# 62.6 ns ± 0 ns per loop (mean ± std. dev. of 2 runs, 250 loops each)

执行次数会n * r 但是统计是根据repeats的次数(r)但是每次重复的"loops"的次数是根据 number (n).

确定

基本上你需要足够大 n 所以循环次数的最小值是准确的 "enough" 代表最快的执行时间,但你也需要足够大 r 以准确 "statistics" 了解 "fastest possible execution time" 测量的可信度(特别是如果您怀疑可能正在发生某些缓存)。

对于表面时间,您应该始终使用 357r(在大多数情况下足够大)并选择 n 尽可能高 - 但不要太高,您可能希望它在合理的时间内完成 :-)

timeit -n 250 <statement>

该语句将执行 3 * 250 = 750 次(-r 默认值为 3)

timeit -n 250 -r 4 <statement>

该语句将执行 4 * 250 = 1000 次

-r - 定时器重复多少次(在上面的例子中,每次使用 -n 250 调用定时器,这意味着执行 250 次)

一种更具统计学意义的解释方式是对某些统计数据(特别是其均值和标准差)的分布进行自举估计,在这种情况下:"r" 可以看作是样本数量和"n"作为每个样本的大小。