在索引作为输入编号的for循环中运行timeit

时间:2014-01-28 01:51:00

标签: python python-2.7 timeit

我试图运行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()

它有效。有什么建议?

1 个答案:

答案 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))