Python timeit module doesn't recognize numpy module

I want to check processing time between 2 identical lists, especially for regular list and numpy list. My code

import timeit import numpy as np t = timeit.Timer("range(1000)") print t.timeit() u = timeit.Timer("np.arange(1000)") print u.timeit() 

The calculation for t fine, but for u NameError: the global name 'np' is not defined.

How do I encode it to get processing time?

+8
python numpy timeit
source share
3 answers

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

It can either take the source code to compile the executed - in this case, the code is executed in a new environment where only the setup code was run, or it can receive the called call, and in this case the called (in your current environment, like any other called) .

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 did import numpy as np does not matter; it does not affect the environment in which np.arange(1000) compiled and executed (and therefore you must include it in the setup=... bit).

In the second case, the fact that you did import numpy as np obviously matters - it affects the environment in which your code is evaluated, including lambda: np.arange(1000) .

+10
source share

Use the setup parameter:

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

To use imported libraries with timeit , you need 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 customize your code, such as importing external libraries or importing functions from your code with from __main__ import func .

+2
source share

All Articles