Artur
Artur

Reputation: 1065

Python timeit module causes an infinite loop

Consider this Python3 code:


def classic_fibonacci(limit: int) -> List[int]:
    nums = []
    curr, nxt = 0, 1

    while curr < limit:
        curr, nxt = nxt, nxt + curr
        nums.append(curr)

    return nums

def classic_fib_profiling():
    for n in classic_fibonacci(limit=1000):
        print(n, end=', ')

if __name__ == '__main__':
    import timeit
    timeit.timeit("classic_fib_profiling()", setup="from __main__ import classic_fib_profiling")

Calling classic_fib_profiling() returns, as expected, a single list of Fibonacci numbers, limited to limit parameter.

Calling it using timeit.timeit, on the other hand, causes the interpreter to go into an infinite loop, never stopping. I wasn't able to find a solution by debugging or searching docs (and SO). Any help would be appreciated.

Upvotes: 3

Views: 1144

Answers (1)

han solo
han solo

Reputation: 6600

It is not going in an infinite loop. It will run the same function number times (default: number=1000000). Just wait for it finish, or provide the number of times the loop should run. Check the arguments for the timeit.timeit function.

Help on function timeit in module timeit:

timeit(stmt='pass', setup='pass', timer=, number=1000000, globals=None) Convenience function to create Timer object and call timeit method.

Change the line from,

>>> timeit.timeit("classic_fib_profiling()", setup="from __main__ import classic_fib_profiling")

to

>>> timeit.timeit("classic_fib_profiling()", setup="from __main__ import classic_fib_profiling", number=1)

and observe :)

Upvotes: 4

Related Questions