I want to use timeit in Python 3.5 to measure two functions. The first one relies on import math
and the second one on from math import log2
. I though I can handle this by passing the appropiate import statement as setup string when calling timeit.repeat
. But I get NameError: name 'math' is not defined
.
I don't want to pass the functions as their name strings. When the functions don't depend on imports, this code here works, but I need them with the calls of math.log2
Looking foward to your answers.
def spam_log_v1():
for _ in range(1000):
math.log2(2)
def spam_log_v2():
for _ in range(1000):
log2(2)
if __name__ == '__main__':
import timeit
repeat = 3
number = 1000
unit = "usec"
unittosec = {"usec": 1e6, "msec": 1000, "sec": 1}
tests = [(spam_log_v1, 'import math'),
(spam_log_v2, 'from math import log2')]
for fct, setup in tests:
res = timeit.repeat(fct, setup=setup, repeat=repeat, number=number)
print("%s: %d loops, best of %d: %.3g %s per loop" %
(fct.__name__, number, repeat,
min(res) / number * unittosec[unit], unit))