Im trying to run timeit to time a python function like so:

for i in range(1, 30):
    print 'The time for ' + str(i) + ' is ' + str(timeit.Timer('Fib(i)', 'from problem1 import Fib').timeit())

global name 'i' is not defined even though I have i defined in the start of the program as global i

When I run timeit like so:

print timeit.Timer('Fib(5)', 'from problem1 import Fib').timeit()

it works. Any suggestions?

有帮助吗?

解决方案

Use string formatting:

for i in range(1, 30):
    t = timeit.Timer('Fib({:d})'.format(i), 'from problem1 import Fib').timeit()
    print('The time for {i:d} is {t:0.2f}'.format(i=i, t=t))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top