首页 > 解决方案 > 为什么ipython魔术函数`%timeit -n1 code_block`会多次执行`code_block`?

问题描述

ipython我正在尝试使用 %timeit魔术功能多次运行特定测试。出于演示目的,我将在这里使用-n1而不是 -n3,并使用一个简单的print(1)函数。

和帮助说明如下%%timeit%timeit

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

-r<R>: repeat the loop iteration <R> times and take the best result.
Default: 3 (the 3 here is a typo in ipython, for which I have submitted a
PR)

但是,如果我执行以下操作:

%%timeit -n1
print(1)

或者

%timeit -n1 print(1)

它实际上1连续打印 7 次,如下所示

In[1]: %timeit -n1 print(1)
1
1
1
1
1
1
1
32.8 µs ± 38.7 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

我期待由于%%timeit/的定义,%timeit它会运行cellorcode一次。

我已经阅读了这篇文章:https ://stackoverflow.com/a/45375047/4752883 ,其中提供了一些有关如何运行的示例以及魔术函数%%timeit的实际源代码 :https ://github.com/ipython/ipython/blob/ ec3d1a11bf26a0962cb2cf55ba263b12ac023183/IPython/core/magics/execution.py#L944ipython%%timeit

他们定义了两种类型的循环: 1)-n<N>和 2) -r<R>

如果我只是使用-n1,它似乎也假定我已经使用过-r7,即 -n1默认为-n1 -r7。这意味着即使我希望它运行 1 次,它仍然会code_block按照 https://github.com/ipython/ipython/blob/ec3d1a11bf26a0962cb2cf55ba263b12ac023183/IPython/core/magics/execution.py#运行 7 次L1021 除非我还指定-n1 -r1.

问题:

  1. 为什么有两种不同的方式来运行code_blockusing-n<N>-r<R>
  2. 有什么区别-n<N>-r<R>为什么这是必要的?

标签: pythonipythontimeit

解决方案


这些参数也在timeit 模块中。

  • -n确定您在计时窗口内运行函数(或块,或其他)的次数。所以秒表开始,代码是运行n时间,然后秒表结束。您应该运行它足够多的时间以使结果有意义(timeit默认为 10 的幂,直到经过 0.2 秒)。
  • -r确定您应该执行多少次重复(其中重复是“启动计时器,运行 n 次,停止计时器”)。由于您的 CPU 调度其他进程等原因,总是会出现一些错误,因此通常您希望运行它几次并取这些时间的最佳值r。(timeit默认为 3,您链接的源代码中的注释表明 ipython 也是如此——但实际代码可能不同意)。

在pseudo-python中,您可以看到如何n以及r影响计时过程:

time_hist = []
for _ in range(r):
    t0 = time.now()              # Start stopwatch (.now() is not a real function)
    for _ in range(n):
        # <your code block>
    t1 = time.now()              # Stop stopwatch

    time_hist.append(t1 - t0)    # Append time delta

 return min(time_hist)           # Return the min of the r deltas   

推荐阅读