python - 为什么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
它会运行cell
orcode
一次。
我已经阅读了这篇文章: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
.
问题:
- 为什么有两种不同的方式来运行
code_block
using-n<N>
和-r<R>
? - 有什么区别
-n<N>
,-r<R>
为什么这是必要的?
解决方案
这些参数也在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
推荐阅读
- ios - ImagePicker 和分配给 ImageView 的问题
- wordpress - 如何按元值订购我的 WP 查询,并且只从不同的元中获取某些值?
- vue.js - 在 Vue-CLI 中使用 PleaseWait.js 加载屏幕
- python - 如何在 BaggingClassifier 中调整 SVM 的参数
- reporting-services - 带有新条目的 SSRS 订阅电子邮件
- javascript - 将其中包含数字数组的字符串转换为实际值
- javascript - 如何改进 div 的这种 Javascript 切换?
- sql-server - 从 API 保存或缓存数据的有效方法是什么?
- python - PythonAnywhere.com 上未启用 Scrapy Item Pipelines
- java - 是否有与 Processing 中的 draw() 等效的 Java?