如何解释 Python 中的 interpret timeit 命令
how to interpret interpret timeit command in Python
例如我有一个列表:
L=[-13, -24, -21, -3, -23, -15, -14, -27, -13, -12]
如果输入 %timeit -n 10 myList = [item for item in L if item < 15]
输出为 10 loops, best of 3: 1.25 µs per loop
如果我输入 myGen = (item for item in L if item < 15)
输出为 1000000 loops, best of 3: 561 ns per loop
我不明白情况 2,为什么生成器需要 1000000 次循环而不是 10 次循环? "best of 3" 是什么意思?我如何计算出每个 commond 所需的总秒数,例如案例 1 的 10*1.25=12.5 us?
您没有在第二个示例中包含 %timeit
的 -n
参数,因此 ipython 根据试验的持续时间改变重复次数 - 运行 需要;被测试的代码段越快,迭代次数越多,以获得更准确的每次迭代时间值。
此外,测试 运行 几次,以尽量减少外部因素(例如,当您的 OS 恰好安排了磁盘缓冲区刷新,其他一切都变得有点慢).这就是 'best of 3' 出现的地方;测试连续 运行 3 次,并选择了最佳时机。
请参阅 %timeit
magic command documentation,其中包括以下选项及其默认行为:
-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
你的第一个例子确实使用了-n 10
所以它运行只有10次。
因为使用生成器表达式创建 generator 对象几乎是即时的,ipython 可以比执行列表推导(必须执行 for
循环并生成一个包含所有结果的列表对象 then )。请记住,在您驱动迭代之前,生成器表达式不会执行 任何 工作。
如果您想比较生成器表达式产生与列表理解相同的结果所需的时间,您必须实际迭代。您可以将表达式传递给 list()
调用以实际生成一个列表:
%timeit -n 10 myGen = (item for item in L if item < 15); list(myGen)
这会更慢,因为生成器的开销比列表理解多一点:
In [1]: L=[-13, -24, -21, -3, -23, -15, -14, -27, -13, -12]
In [2]: %timeit -n 10 myList = [item for item in L if item < 15]
10 loops, best of 3: 1.29 µs per loop
In [3]: %timeit -n 10 myGen = (item for item in L if item < 15); list(myGen)
10 loops, best of 3: 1.72 µs per loop
请注意,您必须在每次测试迭代时重新创建生成器,因为生成器只能产生一次输出。
例如我有一个列表:
L=[-13, -24, -21, -3, -23, -15, -14, -27, -13, -12]
如果输入
%timeit -n 10 myList = [item for item in L if item < 15]
输出为10 loops, best of 3: 1.25 µs per loop
如果我输入
myGen = (item for item in L if item < 15)
输出为1000000 loops, best of 3: 561 ns per loop
我不明白情况 2,为什么生成器需要 1000000 次循环而不是 10 次循环? "best of 3" 是什么意思?我如何计算出每个 commond 所需的总秒数,例如案例 1 的 10*1.25=12.5 us?
您没有在第二个示例中包含 %timeit
的 -n
参数,因此 ipython 根据试验的持续时间改变重复次数 - 运行 需要;被测试的代码段越快,迭代次数越多,以获得更准确的每次迭代时间值。
此外,测试 运行 几次,以尽量减少外部因素(例如,当您的 OS 恰好安排了磁盘缓冲区刷新,其他一切都变得有点慢).这就是 'best of 3' 出现的地方;测试连续 运行 3 次,并选择了最佳时机。
请参阅 %timeit
magic command documentation,其中包括以下选项及其默认行为:
-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
你的第一个例子确实使用了-n 10
所以它运行只有10次。
因为使用生成器表达式创建 generator 对象几乎是即时的,ipython 可以比执行列表推导(必须执行 for
循环并生成一个包含所有结果的列表对象 then )。请记住,在您驱动迭代之前,生成器表达式不会执行 任何 工作。
如果您想比较生成器表达式产生与列表理解相同的结果所需的时间,您必须实际迭代。您可以将表达式传递给 list()
调用以实际生成一个列表:
%timeit -n 10 myGen = (item for item in L if item < 15); list(myGen)
这会更慢,因为生成器的开销比列表理解多一点:
In [1]: L=[-13, -24, -21, -3, -23, -15, -14, -27, -13, -12]
In [2]: %timeit -n 10 myList = [item for item in L if item < 15]
10 loops, best of 3: 1.29 µs per loop
In [3]: %timeit -n 10 myGen = (item for item in L if item < 15); list(myGen)
10 loops, best of 3: 1.72 µs per loop
请注意,您必须在每次测试迭代时重新创建生成器,因为生成器只能产生一次输出。