timeit module in python does not recognize numpy module

血红的双手。 提交于 2019-12-21 03:42:38

问题


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()

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?


回答1:


The timeit.Timer class can be used in two different ways.

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

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; 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).

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.




回答2:


Use setup parameter:

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



回答3:


To use imported libraries with timeit you have to import them using the setup keyword argument (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.



来源:https://stackoverflow.com/questions/21216208/timeit-module-in-python-does-not-recognize-numpy-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!