我正在尝试在 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
它会
运行cell
或code
就一次。
我读过这篇文章: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
.
问题:
- 为什么有两种不同的方式来运行
code_block
使用-n<N>
和-r<R>
? -n<N>
和有什么区别和-r<R>
这是为什么 有必要吗?
最佳答案
这些参数也在 timeit module 中.
-n
确定在计时窗口内运行函数(或 block 或其他内容)的次数。因此,秒表启动,代码运行 n 次,然后秒表结束。您应该运行它足够多的次数,以使结果有意义(timeit
默认为 10 的幂,直到 0.2 秒过去)。-r
确定您应该执行多少次重复(其中重复是“启动计时器,运行 n 次,停止计时器”)。由于您的CPU调度其他进程等原因,总会出现一些错误,因此通常您希望运行它几次,并取这些r
次的最佳值。 (timeit
默认为 3,并且您链接的源代码中的注释表明 ipython 执行相同操作 - 但实际代码可能不同意)。
在伪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
关于python - 为什么ipython魔术函数 `%timeit -n1 code_block`会多次执行 `code_block`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891288/