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) .
abarnert
source share