Python 导入Numpy会增加timeit.repeat中第一次迭代的执行时间

Python 导入Numpy会增加timeit.repeat中第一次迭代的执行时间,python,python-2.7,numpy,benchmarking,Python,Python 2.7,Numpy,Benchmarking,使用来测量一些表达式的执行时间,我意识到如果我事先导入numpy,第一次迭代所需的时间会明显更长。考虑下面的例子: from __future__ import print_function import timeit import numpy as np # comment this line results = timeit.repeat( "d['a']", setup="d = dict(zip('abc', '123'))", repeat=5, numb

使用来测量一些表达式的执行时间,我意识到如果我事先导入
numpy
,第一次迭代所需的时间会明显更长。考虑下面的例子:

from __future__ import print_function

import timeit
import numpy as np  # comment this line

results = timeit.repeat(
    "d['a']",
    setup="d = dict(zip('abc', '123'))",
    repeat=5, number=10**6
)
print(['{:.2e}'.format(x) for x in results])
我得到以下结果:

['5.38e-02', '2.72e-02', '2.70e-02', '2.68e-02', '2.70e-02']
第一次迭代比其余的迭代花费的时间要长得多(我通过多次运行代码来验证这个模式)

现在,当在上述代码中将
import numpy注释为np
行时,计时结果更改如下:

['2.73e-02', '2.71e-02', '2.65e-02', '2.68e-02', '2.66e-02']
这里,第一次迭代的执行时间与其他迭代相当

在Python 3.8中,无论是否导入了Numpy,都不会出现这种行为,因为在Python 3.8中,我获得了类似的计时:

['2.64e-02', '2.89e-02', '2.65e-02', '2.63e-02', '2.63e-02']  # with 'import numpy'
['2.63e-02', '2.56e-02', '2.52e-02', '2.50e-02', '2.51e-02']  # without 'import numpy'
是什么原因导致Python 2.7的执行时间与导入numpy一起增加


详细版本信息:

  • Python 2.7.12:
    numpy==1.14.0
  • Python 3.8.1:
    numpy==1.18.1