3 回答

TA貢獻1829條經驗 獲得超7個贊
奇怪的是,沒有找到一個解決方案使用發(fā)電機來計時。我只是為了自己的目的設計了這個。
這個解決方案:單線程,沒有對象實例化每一個周期,使用生成器的次數(shù),巖石固體計時下降到精確的time模塊(與我從堆棧交換中嘗試過的幾種解決方案不同)。
注:對于Python2.x,替換next(g)下面有g.next().
import time
def do_every(period,f,*args):
def g_tick():
t = time.time()
count = 0
while True:
count += 1
yield max(t + count*period - time.time(),0)
g = g_tick()
while True:
time.sleep(next(g))
f(*args)
def hello(s):
print('hello {} ({:.4f})'.format(s,time.time()))
time.sleep(.3)
do_every(1,hello,'foo')
例如:
hello foo (1421705487.5811)
hello foo (1421705488.5811)
hello foo (1421705489.5809)
hello foo (1421705490.5830)
hello foo (1421705491.5803)
hello foo (1421705492.5808)
hello foo (1421705493.5811)
hello foo (1421705494.5811)
hello foo (1421705495.5810)
hello foo (1421705496.5811)
hello foo (1421705497.5810)
hello foo (1421705498.5810)
hello foo (1421705499.5809)
hello foo (1421705500.5811)
hello foo (1421705501.5811)
hello foo (1421705502.5811)
hello foo (1421705503.5810)
請注意,此示例包括CPU在每段時間進行3秒鐘的其他操作的模擬。如果你每次都把它改為隨機的,那就無所謂了。中的最大值yield線起保護作用sleep如果調用函數(shù)的時間比指定的時間長,則從負數(shù)開始。在這種情況下,它將立即執(zhí)行,并在下一次執(zhí)行的時間上彌補所損失的時間。
添加回答
舉報