为什么Python的timeit()会无休止地执行?
当尝试使用 Python 内置模块“timeit”时,如下所示:
timeit.Timer('print "hi"').timeit()
它打印不止一行;这是为什么?它不断地打印“hi”:
hi
hi
hi
hi
...
When trying to use the Python built-in module 'timeit' as follows:
timeit.Timer('print "hi"').timeit()
it prints more than one line; why is that? It keeps printing "hi" endlessly:
hi
hi
hi
hi
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
timeit
旨在测试极短的代码片段,因此它会多次运行代码并取平均值。默认情况下,它运行 1000000 次。您可以通过运行它来更改此设置,如下所示:
timeit
is designed to test extremely short code snippets, so it runs the code many times and averages them. As a default, it runs it 1000000 times.You can change this by running it as follows:
如果您查看文档,您将看到该声明默认执行1000000次。
如果您只想运行它 2 次,则可以将 2 传递给
Timer
类的timeit()
方法。If you look at the docs, you will see that the statement will default to executing 1000000 times.
If you only want to run it 2 times, you would pass a 2 to the
timeit()
method of theTimer
class.