我试图运行timeit来计算这样的python函数:
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
即使我已经在程序开头定义为global i
当我像这样运行timeit时:
print timeit.Timer('Fib(5)', 'from problem1 import Fib').timeit()
它有效。有什么建议?
答案 0 :(得分:4)
使用字符串格式:
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))