Python:启动和停止计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27594926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Start and stop timer
提问by hnvasa
I have a code which runs for more than 1,000 iterations. I want te implement a timer that starts before the code starts executing and stops after the execution of the code is done. By this i simply want to measure the time taken for the code to complete the iterations. How do I implement such a timer in python?
我有一个运行超过 1,000 次迭代的代码。我想要实现一个计时器,该计时器在代码开始执行之前启动并在代码执行完成后停止。通过这个,我只想测量代码完成迭代所花费的时间。我如何在 python 中实现这样的计时器?
Code Structure:
代码结构:
Start timer
启动计时器
//Code
//代码
Stop Timer
停止计时器
Thanks in advance!
提前致谢!
采纳答案by John Cipponeri
Here's an answer to the same question you're asking: https://stackoverflow.com/a/2866456/4380308
这是您提出的同一问题的答案:https: //stackoverflow.com/a/2866456/4380308
import time
t0 = time.time()
code_block
t1 = time.time()
total = t1-t0
Or you can use the 'timeit' module: https://stackoverflow.com/a/2866460/4380308
或者您可以使用“timeit”模块:https: //stackoverflow.com/a/2866460/4380308
timeit.timeit('foobar()', number=1000)