Domanda

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?

È stato utile?

Soluzione

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))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top