Python - 在精确时间间隔内循环

4

我希望能够在精确的时间间隔(约为15秒)内运行一段代码。最初我使用了time.sleep(),但问题在于代码需要一秒左右才能运行,所以它会失去同步。

我写了下面这段代码,但感觉不太整洁,因为我不喜欢使用while循环。有更好的方法吗?

import datetime as dt
import numpy as np

iterations = 100
tstep = dt.timedelta(seconds=5)
for i in np.arange(iterations):
    startTime = dt.datetime.now()
    myfunction(doesloadsofcoolthings)
    while dt.datetime.now() < startTime + tstep:
        1==1
3个回答

8
理想情况下,可以使用线程来完成此操作。您可以尝试以下方式:
import threading
interval = 15

def myPeriodicFunction():
    print "This loops on a timer every %d seconds" % interval

def startTimer():
    threading.Timer(interval, startTimer).start()
    myPeriodicFunction()

那么你只需要调用即可。
startTimer()

为了启动循环计时器。

这是否意味着如果进程仍在运行,则会在不同的 CPU 线程上启动下一个进程? - AndyMoore
这并不是精确的。我在每个循环中经历了大约0.01秒的偏移。我的周期性函数只是打印(datetime.now())。 - cheesus

2
您可以使用一个简单的 bash 命令行:
watch -n 15m python yourcode.py

2
考虑追踪代码运行所需的时间(使用 timer() 函数),然后在完成后暂停15-exec_time秒。
start = datetime.now()
do_many_important_things()
end = datetime.now()

exec_time = end - start
time.sleep(15-exec_time.total_seconds())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接