简体   繁体   English

Python timeit模块导致无限循环

[英]Python timeit module causes an infinite loop

Consider this Python3 code: 考虑以下Python3代码:


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. 如预期的那样,调用classic_fib_profiling()返回一个斐波纳契数的单个列表,仅限于limit参数。

Calling it using timeit.timeit , on the other hand, causes the interpreter to go into an infinite loop, never stopping. 另一方面,使用timeit.timeit调用它会使解释器进入无限循环,永不停止。 I wasn't able to find a solution by debugging or searching docs (and SO). 我无法通过调试或搜索文档(和SO)找到解决方案。 Any help would be appreciated. 任何帮助,将不胜感激。

It is not going in an infinite loop. 它不会陷入无限循环。 It will run the same function number times (default: number=1000000 ). 它将运行相同功能的number时间(默认: 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. 检查timeit.timeit函数的参数。

Help on function timeit in module timeit: 模块timeit中有关函数timeit的帮助:

timeit(stmt='pass', setup='pass', timer=, number=1000000, globals=None) Convenience function to create Timer object and call timeit method. timeit(stmt ='pass',setup ='pass',timer =,number = 1000000,globals = None)便利功能,用于创建Timer对象并调用timeit方法。

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 :) 并观察:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM