gpt4 book ai didi

python - 在 ipython 中使用 timeit 的问题

转载 作者:行者123 更新时间:2023-11-30 23:32:15 33 4
gpt4 key购买 nike

我很快就尝试对 ipython 中的 2 个函数进行计时,m1()m2() 使用 2 种不同的实现来执行相同的任务。

In [23]: %timeit for x in range(100): m1(a)
10000 loops, best of 3: 57.6 us per loop

In [24]: %timeit for x in range(100): m2(a)
10000 loops, best of 3: 108 us per loop

结果:第一个实现几乎快了 2 倍。到目前为止,一切顺利。

出于好奇,我更改了上面 for 循环的范围,现在我不知道输出的意义。

In [25]: %timeit for x in range(1): m2(a)
1000000 loops, best of 3: 1.29 us per loop

In [26]: %timeit for x in range(10): m2(a)
100000 loops, best of 3: 10.8 us per loop

In [27]: %timeit for x in range(1000): m2(a)
1000 loops, best of 3: 1.06 ms per loop

for 循环到底在做什么?为什么随着范围值的增加,循环次数的值会减少?

PS:我使用的是this作为引用。另外,如果标题不能准确表达我的问题,请将标题修改为更好的内容。

最佳答案

timeit 正在计算整个 block 的执行时间。

所以你看到的是:

  • 运行 m2(a) 1 次需要 1.29 us
  • 运行 m2(a) 10 次需要 10.8 us
  • 运行 m2(a) 1000 次需要 1.06 毫秒

这是有道理的,因为1.06ms = 1060 us,大约是基线的 1000 倍(10.8 us 大约是基线的 10 倍)

对于循环次数,timeit 的目标是在合理的时间内运行:

$ python -mtimeit -h
...
If -n is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.

关于python - 在 ipython 中使用 timeit 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19473800/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com