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

标签 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)

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

%%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它会 运行cellcode就一次。

我读过这篇文章:https://stackoverflow.com/a/45375047/4752883 其中给出了一些示例 %%timeit运行和ipython的实际源代码神奇功能%%timeit 这里:https://github.com/ipython/ipython/blob/ec3d1a11bf26a0962cb2cf55ba263b12ac023183/IPython/core/magics/execution.py#L944

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

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

问题:

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

最佳答案

这些参数也在 timeit module 中.

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

在伪python中,您可以看到nr如何影响计时过程:

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   

关于python - 为什么ipython魔术函数 `%timeit -n1 code_block`会多次执行 `code_block`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891288/

相关文章:

python - Python 中的 %timeit 是什么?

python - timeit.timeit 以科学计数法返回时间?

python - IPython 手动迭代主循环?

python - 如何从脚本运行 IPython 魔法(或计时 Python 脚本)

python - 尝试在 Python 中为我的 sqrt 函数计时

python - 模块未找到错误: Correct setup

python - 协议(protocol)错误,得到 "H"作为回复类型字节

python - 如何在子流程模块中使用列表中的索引?

python - Jython : SyntaxError: invalid syntax

python - 具有调试和 iPython 集成的 Python IDE?