簡體   English   中英

如何在python上創建一個計時器

[英]How to create a timer on python

我正在創建一個代碼,要求程序計算運行的時間,然后顯示時間。 它基本上是一個在后台運行的計時器,我可以調用它來顯示代碼運行的時間。 我該怎么做呢?

您記錄開始時間,然后計算開始時間和當前時間之間的差異。

由於平台差異,為了精確,您要使用timeit.default_timer callable

from timeit import default_timer

start = default_timer()

# do stuff

duration = default_timer() - start

這為您提供了掛鍾持續時間(以秒為單位)作為浮點值。

演示:

>>> from timeit import default_timer
>>> start = default_timer()
>>> # Martijn reads another post somewhere
... 
>>> print default_timer() - start
19.1996181011

這在python中很容易

import time
start_time=time.time()
#do something
end_time=time.time()-start_time

結果end_time將以秒為單位

我這樣做了,這可能對你有幫助

from timeit import default_timer

timerPool = {}
TIMER_RUNNING = 1
TIMER_STOPPED = 0
TIMER_IDLE = 2


"""
Initilialize the timer like below if any new timer to be added
"""
"""
required initialization for "eightSecTimer_Id" timer
"""
timerPool['eightSecTimer_Id'] = {}
timerPool['eightSecTimer_Id']['state'] = TIMER_IDLE
timerPool['eightSecTimer_Id']['start'] = 0
timerPool['eightSecTimer_Id']['duration'] = 0
timerPool['eightSecTimer_Id']['time'] = 0

"""
required initialization for "fiveSecTimer_Id" timer
"""
timerPool['fiveSecTimer_Id'] = {}
timerPool['fiveSecTimer_Id']['state'] = TIMER_IDLE
timerPool['fiveSecTimer_Id']['start'] = 0
timerPool['fiveSecTimer_Id']['duration'] = 0
timerPool['fiveSecTimer_Id']['time'] = 0

"""
Interface to start the timer
"""
def StartTimer(Id,time):
    timerPool[Id]['time'] = time
    timerPool[Id]
    if (timerPool[Id]['state'] == TIMER_IDLE) or (timerPool[Id]['state'] == TIMER_STOPPED):
        timerPool[Id]['start'] = default_timer()
        timerPool[Id]['state'] = TIMER_RUNNING
    return timerPool[Id]['state']

"""
Interface to get the timer status.
Return "TIMER_STOPPED" when timer completed
Return "TIMER_IDLE" after timer completed on consecutive call of this function
"""

def GetTimerState(Id):
    time = timerPool[Id]['time']
    if timerPool[Id]['state'] == TIMER_RUNNING:
        timerPool[Id]['duration'] = default_timer() - timerPool[Id]['start']
    else:
        None
    if timerPool[Id]['state'] == TIMER_STOPPED:
        timerPool[Id]['state'] = TIMER_IDLE

    if  timerPool[Id]['duration'] >= time:
        timerPool[Id]['state'] = TIMER_STOPPED
        timerPool[Id]['duration'] = 0
    return timerPool[Id]['state'] 

"""
Below is how to use.
"""
StartTimer('fiveSecTimer_Id',5)
StartTimer('eightSecTimer_Id',8)

while True:
    if GetTimerState('fiveSecTimer_Id') == TIMER_STOPPED:
        print "5 sec Timer Stopped"
    if GetTimerState('eightSecTimer_Id') == TIMER_STOPPED:
        print "8 sec Timer Stopped"        
    sleep (.5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM