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.