IPython中%time和%timeit之间的不一致 [英] Inconsistency between %time and %timeit in IPython

查看:878
本文介绍了IPython中%time和%timeit之间的不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我无法解释的奇怪情况。这是我的测试时间生成大量元组列表:

I am confronted to a weird situation that I can't explain. Here is my test timing the generation of a large list of tuples:

In [1]: def get_list_of_tuples():
   ...:     return [(i,) for i in range(10**6)]
   ...:

In [2]: %time res = get_list_of_tuples()
CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 s
Wall time: 0.98 s

In [3]: %timeit res = get_list_of_tuples()
1 loops, best of 3: 92.1 ms per loop

如您所见,生成这个庞大的元组列表只需不到一秒钟。 timeit报告执行时间约为0.1秒。为什么这两个报告有这么大的差异?

As you can see, the generation of this large list of tuples takes just below a second. timeit reports the execution time to be around 0.1 second. Why is there such a big difference in the two reports?

(在IPython 0.11,Python 2.6.5上测试过。)

(Tested on IPython 0.11, Python 2.6.5.)

推荐答案

主要区别在于默认情况下,timeit()在定时期间临时关闭垃圾收集。

The main difference is because "by default, timeit() temporarily turns off garbage collection during the timing".

转动垃圾收集返回的结果类似于问题,即垃圾收集执行的时间比没有收集的时间大:

Turning the garbage collection returns results similar to the one shown in the question, i.e. the time of execution with garbage collection is magnitude bigger than the one without:

In [1]: import timeit

# Garbage collection on.
In [2]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', 'gc.enable()', number=N) / N
Out[2]: 0.74884700775146484
# 749 ms per loop.

# Garbage collection off.
In [3]: N = 10; timeit.timeit('[(i,) for i in range(10**6)]', number=N) / N
Out[3]: 0.15906109809875488
# 159 ms per loop.

这篇关于IPython中%time和%timeit之间的不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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