首页 > 解决方案 > 为什么从 /sys/bus/... 读取需要这么多时间?

问题描述

我正在做一个需要来自温度传感器的传感器数据的项目。在使用 open() 然后 read() 访问文件时,我们发现它花费了太长时间。我们已经隔离了 read() 花费最多时间(大约 1 秒)的问题。是否有更快的替代 read() 或者我使用不正确?代码:

import time, os, socket

#External thermometer address: 28-031897792ede

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

temp_sensor = '/sys/bus/w1/devices/28-031897792ede/w1_slave'

def temp_raw():
    f = open(temp_sensor, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():

    lines = temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        lines = temp_raw()

    temp_output = lines[1].find('t=')

    if temp_output != -1:
        temp_string = lines [1].strip()[temp_output+2:]
        temp_c = float(temp_string) / 1000.0
        return round(temp_c, 1)

while True:
    temp_raw()

标签: pythonpython-3.xread-write

解决方案


您正在打开一个不是真正的常规文件系统文件的文件——它是一个字符设备。在 Linux 上,设备节点的系统调用直接由特定的驱动程序实现,该驱动程序注册以处理主要/次要数字对,因此它们的性能取决于该驱动程序的操作系统实现。

高延迟对w1-therm驱动程序来说很常见;无论您使用哪种编程语言,它都会发生。

根据https://www.maximintegrated.com/en/products/sensors/DS18B20.html上的硬件数据表,生成 12 位输出时的刷新率约为 750 毫秒。因此,即使其他一切都绝对完美,您每次读取的温度大约是 3/4 秒。

坦率地说,在温度传感器的情况下,更快的刷新率是没有意义的——如果设备本身的物理温度变化如此之快以至于您需要的不仅仅是每秒测量一次(考虑到热量实际传导到传感器),你有更大的问题。


推荐阅读