I need to time the execution of a function across variable amounts of data.
def foo(raw_data):
preprocessed_data = preprocess_data(raw_data)
time = timeit.Timer('module.expensive_func(preprocessed_data)', 'import module').timeit()
However, preprocessed_data
is not a global variable. It cannot be imported with from __main__
. It is local to this subroutine.
How can i import data
into the timeit.Timer
environment?
time = timeit.Timer('module.expensive_func(data)', 'import module;data = generate_data()').timeit()
? Also, if you need something more complicated you may actually want a profiler. – Richardricharda'import module;from __main__ import otherdata1, othedata2;data = generate_data()'
You can shove as much code as you want inside that bit of setup code. If you have a lot of code for setup define setup as a multiline string before thetimeit
call. – Richardrichardatimeit
module: https://mcmap.net/q/46595/-how-to-use-timeit-module – Butyrate