[英]time.sleep inside a while loop seems to not working correctly
我正在使用 phidget bridge 4 输入来读取称重传感器。 我试图以 1 Hz 的频率获取数据,因此我在 while 循环中使用time.sleep(1)
根据需要每秒读取数据。 为了确保我在 1 Hz,我正在打印我的值,而actuel time - the time of the beginning of the script
并且在每个循环中似乎超过 1000 毫秒。
代码 :
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
import time
start_time = round(time.time()*1000)
A1 = -6.147057832630E-06
B1 = -0.000288253826519
def onVoltageRatioChange(self, voltageRatio):
Masse = (voltageRatio - (B1) ) / (A1)
self.masse = Masse
def runningChannel(channel, dataInterval):
voltageRatioInput = VoltageRatioInput()
voltageRatioInput.setChannel(channel)
voltageRatioInput.setOnVoltageRatioChangeHandler(onVoltageRatioChange)
voltageRatioInput.openWaitForAttachment(5000)
voltageRatioInput.close()
return voltageRatioInput.masse
if __name__ == '__main__':
while True:
print(str(round(time.time()*1000) - start_time) + " : " + str(runningChannel(1, 1000)))
time.sleep(1)
安慰 :
0 : -0.6478727917378451
1353 : -0.7766034823455521
2530 : -0.648175863557032
3914 : -0.7572446275502878
5089 : -0.6493878254748858
6474 : -0.6990053837124224
7650 : -0.6493878254748858
9033 : -0.8542015809786906
10209 : -0.6509030218913868
您忘记了runningChannel()
调用也需要一些时间来执行。
要每秒做某事(仍然大约),您可以使用此循环:
import time
while True:
start_time = time.time()
# your operations here
time.sleep(1 - (time.time() - start_time))
如果您的操作需要超过一秒钟,它显然会失败
看起来您的函数可能需要一段时间才能返回(例如openWaitForAttachment(5000)
)。 将其添加到您有意添加的 1 秒延迟中,您会得到始终略大于 1 秒的延迟。 如果你想解决这个问题,你必须跟踪时间(例如,你可以在每次迭代开始时记录时间,在你的逻辑运行后只等待剩余的时间)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.