How do I ensure that a Python while-loop takes a particular amount of time to run?

后端 未结 3 1415
南旧
南旧 2021-01-01 03:37

I\'m reading serial data with a while loop. However, I have no control over the sample rate.

The code itself seems to take 0.2s to run, so I know I won\'t be able to

3条回答
  •  星月不相逢
    2021-01-01 04:01

    At the beginning of the loop check if the appropriate amount of time has passed. If it has not, sleep.

    # Set up initial conditions for sample_time outside the loop
    sample_period = ???
    next_min_time = 0
    while True:
        sample_time = time.time() - zero
        if sample_time < next_min_time:
            time.sleep(next_min_time - sample_time)
            continue
        # read and print a line
        sample_value = ser.readline()
        sample_line = str(sample_time)+','+str(sample_value)
        outfile.write(sample_line)
        print 'time: {}, value: {}'.format(sample_time, sample_value)
        next_min_time = sample_time + sample_period
    

提交回复
热议问题