Just a note: you need to use timeit.Timer
instead of timeit.timer
or you will get AttributeError: module 'timeit' has no attribute 'timer'
although you might as well use timeit.timeit
which is useful for single use timing.
I'd recommend looking at How to use timeit module for efficient ways to use the timeit
module, specifically using the from __main__ import
syntax:
def function(stuff):
NotImplemented
def setup():
NotImplemented
setup_code = """
from __main__ import function, setup
data = setup()
"""
func_code = "function(data)"
result = timeit.timeit(func_code,setup_code)
This way the setup
function is called to generate the necessary data for the benchmark. Because it is a function it also has access to the global namespace in your module, so it can use information created in the main program in part of its code:
import timeit
def function(stuff):
NotImplemented
def setup():
print("the setup_data is:",setup_data)
setup_code = """
from __main__ import function, setup
data = setup()
"""
func_code = "function(data)"
for i in range(4):
setup_data = i
result = timeit.timeit(func_code,setup_code)
print("result is",result)
So just define setup_data
as the data necessary for the setup (dimensions of matrix for example) before running timeit.timeit
and you are good to go!
It makes sense to use repeat
instead of timeit
if you want to run the setup multiple times for the benchmarks but not every time.
For example lets say you have a sorting algorithm that varies in speed depending on how close to sorted the list is already. if you just use timeit
the results could vary by a lot since after setup it will use the same list every time. You also wouldn't want to generate a list every pass since it would interfere with the actual benchmark.
So in that case it would make sense to use repeat
to sort different lists without including the list creation in the benchmark, plus you can then use the entries to look at the max
or min
times and average etc.