简体   繁体   English

while 循环中的 time.sleep 似乎无法正常工作

[英]time.sleep inside a while loop seems to not working correctly

I am using the phidget bridge 4 input to read load cell.我正在使用 phidget bridge 4 输入来读取称重传感器。 I am trying to acquire the data at 1 Hz so I am using time.sleep(1) inside a while loop to read the data every second as needed.我试图以 1 Hz 的频率获取数据,因此我在 while 循环中使用time.sleep(1)根据需要每秒读取数据。 To be sure I am at 1 Hz, I am printing my value while the actuel time - the time of the beginning of the script and it appears to be more than 1000ms at each loop.为了确保我在 1 Hz,我正在打印我的值,而actuel time - the time of the beginning of the script并且在每个循环中似乎超过 1000 毫秒。

Code :代码 :

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)

Console :安慰 :

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

You are forgetting that the runningChannel() call also takes some times to execute.您忘记了runningChannel()调用也需要一些时间来执行。
To do something (still approximately) every second, you can use this loop:要每秒做某事(仍然大约),您可以使用此循环:

import time
while True:
    start_time = time.time()
    # your operations here
    time.sleep(1 - (time.time() - start_time))

It obviously will fail, if your operation takes more than a second如果您的操作需要超过一秒钟,它显然会失败

It seems like you have functions that might take a while to return (eg openWaitForAttachment(5000) ).看起来您的函数可能需要一段时间才能返回(例如openWaitForAttachment(5000) )。 add that to the 1 second delay you added on purpose, and you get a delay that is always slightly bigger than 1 second.将其添加到您有意添加的 1 秒延迟中,您会得到始终略大于 1 秒的延迟。 If you want to get over this problem, you'll have to keep track of time (for example, you can log the time at the start of each iteration, and after your logic ran wait only the remaining time)如果你想解决这个问题,你必须跟踪时间(例如,你可以在每次迭代开始时记录时间,在你的逻辑运行后只等待剩余的时间)

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

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