python中的timeit模块无法识别numpy模块 [英] timeit module in python does not recognize numpy module
问题描述
我想测试2个相同列表之间的处理时间,特别是对于普通列表和numpy列表.我的代码是
I want to test the processing time between 2 identical lists, specifically for a normal list and a numpy list. My code is
import timeit
import numpy as np
t = timeit.Timer("range(1000)")
print t.timeit()
u = timeit.Timer("np.arange(1000)")
print u.timeit()
对于t
的计算很好,但是对于u
的NameError:列出了未定义的全局名称'np'.
Calculation for t
is fine, but for u
NameError: global name 'np' is not defined is listed.
我应该如何编码以获得处理时间?
How should I code it to get the processing time?
推荐答案
timeit.Timer
类可以以两种不同的方式使用.
The timeit.Timer
class can be used in two different ways.
它可以采用源代码进行编译执行-在这种情况下,该代码在仅运行setup
代码的全新环境中执行,或者可以采用可调用的形式,在这种情况下,可调用的只是被调用(在您当前的环境中,与其他任何可调用对象一样).
It can either take source code to be compiled an executed—in which case, the code is executed in a fresh environment where only the setup
code has been run, or it can take a callable, in which case the callable is just called (in your current environment, like any other callable).
因此,您有两个选择:
u = timeit.Timer("np.arange(1000)", setup='import numpy as np')
…或…
u = timeit.Timer(lambda: np.arange(1000))
在第一种情况下,您恰好完成了import numpy as np
的事实是无关紧要的;它对编译和执行np.arange(1000)
的环境没有影响(因此必须将其包含在setup=...
位中).
In the first case, the fact that you happen to have done an import numpy as np
is irrelevant; it has no effect on the environment in which np.arange(1000)
is compiled and executed (and thus you must include it in the setup=...
bit).
在第二种情况下,您已经完成了import numpy as np
显然是 的事实-它会影响您的代码(包括lambda: np.arange(1000)
)得到评估的环境.
In the second case, the fact that you've done an import numpy as np
obviously is relevant—it affects the environment in which your code, including the lambda: np.arange(1000)
, gets evaluated.
这篇关于python中的timeit模块无法识别numpy模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!