如何确保Python while循环需要特定的时间才能运行?

Chr*_*ris 5 python serial-port while-loop pyserial python-2.7

我正在使用while循环读取串行数据.但是,我无法控制采样率.

代码本身似乎需要花费0.2秒才能运行,所以我知道我将无法以更快的速度运行.但我希望能够准确控制我采样的速度.

我觉得我可以使用'sleep'来做到这一点,但问题是有可能在不同的点上循环本身需要更长的时间来读取(取决于通过串行数据传输的精确内容),所以代码会有弥补平衡.

例如,假设我想每1秒采样一次,并且循环需要0.2s到0.3s才能运行.我的代码需要足够智能才能睡眠0.8秒(如果循环需要0.2秒)或0.7秒(如果循环需要0.3秒).

import serial
import csv
import time

#open serial stream
    while True:

        #read and print a line
        sample_value=ser.readline()
        sample_time=time.time()-zero
        sample_line=str(sample_time)+','+str(sample_value)
        outfile.write(sample_line)
        print 'time: ',sample_time,', value: ',sample_value
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 11

只需测量代码运行循环的每次迭代所花费的时间,并sleep相应地:

import time

while True:
    now = time.time()            # get the time
    do_something()               # do your stuff
    elapsed = time.time() - now  # how long was it running?
    time.sleep(1.-elapsed)       # sleep accordingly so the full iteration takes 1 second
Run Code Online (Sandbox Code Playgroud)

当然不是100%完美(可能不时一毫秒或另一个),但我想它已经足够好了.


另一个好方法是使用双绞线LoopingCall:

from twisted.internet import task
from twisted.internet import reactor

def do_something():
    pass # do your work here

task.LoopingCall(do_something).start(1.0)
reactor.run()
Run Code Online (Sandbox Code Playgroud)