简体   繁体   English

如何在 Python 中实现计时功能?

[英]How to implement a timing function in Python?

I am thinking to implement a function like below:我正在考虑实现如下功能:

timeout = 60 second
timer = 0
while (timer not reach timeout):
    do somthing
    if another thing happened:
         reset timer to 0

My question is how to implement the timer stuff?我的问题是如何实现计时器的东西? Multiple thread or a particular lib?多线程或特定的库?

I hope the solution is based on the python built-in lib rather than some third-part fancy package.我希望解决方案是基于 python 内置库而不是一些第三方花哨的包。

I don't think you need threads for what you have described.我认为您不需要针对您所描述的线程。

import time

timeout = 60
timer = time.clock()
while timer + timeout < time.clock():
    do somthing
    if another thing happened:
        timer = time.clock()

Here, you check every iteration.在这里,您检查每次迭代。

The only reason you would need a thread is if you wanted to stop in the middle of an iteration if something was taking too long.您需要线程的唯一原因是,如果某件事花费太长时间,您想迭代中间停止。

I use the following idiom:我使用以下习语:

from time import time, sleep

timeout = 10 # seconds

start_doing_stuff()
start = time()
while time() - start < timeout:
    if done_doing_stuff():
        break
    print "Timeout not hit. Keep going."
    sleep(1) # Don't thrash the processor
else:
    print "Timeout elapsed."
    # Handle errors, cleanup, etc

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

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