为什么 ipython 魔术函数 `%timeit -n1 code_block` 多次执行 `code_block`?

alp*_*989 3 python ipython timeit

我正在尝试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)
Run Code Online (Sandbox Code Playgroud)

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

%%timeit -n1
print(1)
Run Code Online (Sandbox Code Playgroud)

或者

%timeit -n1 print(1)
Run Code Online (Sandbox Code Playgroud)

它实际上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)
Run Code Online (Sandbox Code Playgroud)

我期待因为%%timeit/的定义%timeit它会运行cellcode只运行一次。

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

他们定义了两种类型的循环: 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>为什么是这个必要吗?

jed*_*rds 6

这些参数也在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   
Run Code Online (Sandbox Code Playgroud)