PySerial readlines() 消耗的 CPU 时间是 read() 的 25 倍

PySerial's readlines() consumes 25x times as much CPU time as read()

我正在使用 pyserial 通过串口读取持续不断的数据流:

import serial
s = serial.Serial('/dev/ttyACM0', 9600)

如果我使用 .read 方法,就像这样

while True:
    print(s.read(1000))

消耗1-2%左右CPU

但是如果我开始把它们放在一个列表中,这样会更方便,就像那样

while True:
    print(s.readlines(1000))

CPU 使用率突然飙升至 50%,这似乎有点不合理,只是在新行中拆分了输出差异。

我做错了什么吗,有没有办法让 readlines() 方法更谨慎地使用 CPU?

谢谢

我的猜测是 readlinesreadline 忙于轮询串行行以查找新字符以满足您获得完整行(或多行)的请求,而 .read只有在确实有新数据时才会读取 return 。您可能必须自己实现缓冲和分割线(代码未经测试,因为我现在在串行线上没有任何东西:-)):

import serial


def read_lines(s, sep=b"\n"):
    buffer = b""
    while True:
        buffer += s.read(1000)
        while sep in buffer:
            line, _, buffer = buffer.partition(sep)
            yield line


s = serial.Serial("/dev/ttyACM0", 9600)

for line in read_lines(s):
    print(line)