在ipython中使用timeit的问题 [英] Issues with using timeit in ipython

查看:199
本文介绍了在ipython中使用timeit的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很快就尝试在ipython中为2个函数计时,m1()m2()用2种不同的实现方式执行相同的任务.

I was quickly trying to time 2 functions in ipython, m1() and m2() doing the same task with 2 different implementation.

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倍.到目前为止,一切都很好.

Result: the first implementation is almost 2x faster. So far, so good.

出于好奇,我更改了上面的for循环的范围,现在我不知所措了.

Out of curiousity, I changed the range of the for loop above, and now I am at a loss making sense of the output.

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循环到底是做什么的?为什么循环次数的值随着范围值的增加而减小?

What exactly is the for loop doing here? And why do the value of the number of loops decrease on increasing the range value?

PS:我使用的是作为参考.另外,如果标题不能准确传达我的问题,请对其进行更好的编辑.

PS: I was using this as the reference. Also, please edit the title to something better if it doesn't exactly convey my question.

推荐答案

timeit正在计算整个块的执行时间.

timeit is counting the execution time for the entire block.

所以您看到的是:

  • 运行m2(a) 1次需要1.29 us
  • 运行m2(a) 10次需要10.8 us
  • 运行m2(a) 1000次需要1.06 ms
  • running m2(a) 1 time takes 1.29 us
  • running m2(a) 10 times takes 10.8 us
  • running m2(a) 1000 times takes 1.06 ms

1.06ms = 1060 us开始,这大概是基线的1000倍(而10.8 us大约是基线的10倍)

Which makes some sense, since 1.06ms = 1060 us, roughly 1000x the baseline (and 10.8 us is roughly 10x the baseline)

关于循环数,timeit旨在在合理的时间内运行:

As for the number of loops, timeit aims to run within a reasonable time:

$ 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.

这篇关于在ipython中使用timeit的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆