Using timeit, I have a setup code block which sets up a data structure filled with dummy data, and I have two statements (say, test1 and test2) which retrieve data from this data structure in different ways.
When I do
t = timeit.Timer(test1, setup)
print t.timeit(3000)
t = timeit.Timer(test2, setup)
print t.timeit(3000)
I notice that the setup is run twice, once for each test. Is it possible to make the two tests share the same setup, i.e. run setup code block exactly once and use the exactly the same data structure created for both tests?
The easiest way to achieve this is to put the setup code into a module
setup.py, and then useas
setupparameter totimeit.timeit(). (Note that wildcard imports won’t work correctly in that situation.)If you don’t want to use a separate module, put the code in the main module and use