简体   繁体   English

python中的timeit模块无法识别numpy模块

[英]timeit module in python does not recognize numpy module

I want to test the processing time between 2 identical lists, specifically for a normal list and a numpy list. 我想测试两个相同列表之间的处理时间,特别是正常列表和numpy列表。 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()

Calculation for t is fine, but for u NameError: global name 'np' is not defined is listed. t计算很好,但对于u NameError:未列出全局名称'np'。

How should I code it to get the processing time? 我应该如何编码以获得处理时间?

The timeit.Timer class can be used in two different ways. timeit.Timer类可以以两种不同的方式使用。

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). 它可以将源代码编译为执行 - 在这种情况下,代码在只运行setup代码的新环境中执行,或者它可以采用可调用的,在这种情况下可调用的是可调用的(在这种情况下)你当前的环境,就像任何其他可调用的一样)。

So, you have two options: 所以,你有两个选择:

u = timeit.Timer("np.arange(1000)", setup='import numpy as np')

… or … … 要么 …

u = timeit.Timer(lambda: np.arange(1000))

In the first case, the fact that you happen to have done an import numpy as np is irrelevant; 在第一种情况下,你碰巧做了一个import numpy as np的事实是无关紧要的; 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). 它对编译和执行np.arange(1000)的环境没有影响(因此你必须将它包含在setup=... )。

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. 在第二种情况下,你import numpy as np完成了一个import numpy as np的事实显然相关的 - 它会影响你的代码(包括lambda: np.arange(1000)被评估的环境。

To use imported libraries with timeit you have to import them using the setup keyword argument ( docs ): 要使用带有timeit导入库,您必须使用setup关键字参数( docs )导入它们:

import timeit

# Doesn't require setup kwarg as range doesn't need to be imported.
t = timeit.Timer("range(1000)")
print t.timeit()

# Requires the import of numpy (as np) through the setup kwarg.
u = timeit.Timer("np.arange(1000)", setup = 'import numpy as np')
print(u.timeit())

The setup keyword argument allows you to setup your code, such as importing external libraries or importing functions from your code through the use of from __main__ import func . setup关键字参数允许您设置代码,例如通过使用from __main__ import func导入外部库或从代码from __main__ import func

使用setup参数:

u = timeit.Timer("np.arange(1000)", setup='import numpy as np')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM