python - 为什么从 /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()
解决方案
您正在打开一个不是真正的常规文件系统文件的文件——它是一个字符设备。在 Linux 上,设备节点的系统调用直接由特定的驱动程序实现,该驱动程序注册以处理主要/次要数字对,因此它们的性能取决于该驱动程序的操作系统实现。
高延迟对w1-therm
驱动程序来说很常见;无论您使用哪种编程语言,它都会发生。
根据https://www.maximintegrated.com/en/products/sensors/DS18B20.html上的硬件数据表,生成 12 位输出时的刷新率约为 750 毫秒。因此,即使其他一切都绝对完美,您每次读取的温度大约是 3/4 秒。
坦率地说,在温度传感器的情况下,更快的刷新率是没有意义的——如果设备本身的物理温度变化如此之快以至于您需要的不仅仅是每秒测量一次(考虑到热量实际传导到传感器),你有更大的问题。
推荐阅读
- networking - Packer Tracer:WLAN 配置与多个 VLAN
- syntax-error - Sieve 语言语法错误帮助“如果附近有分号的标识符”
- typescript - 数字的枚举类型突变,但不是字符串?
- android - 无法创建 ViewModel 的实例
- php - 如何命名根据不同条件动态创建的单选按钮组
- flutter - Flutter Framework 如何以及在何处内部调用 StatefulWidget 的 state 的 build 方法?
- scala - 将数据从一个现有行复制到另一个现有行,除了 scala 数据框中的 3 列
- python - 如何使用 scikit-learn 中的 ColumnTransformer 将多个转换应用于同一列
- c++ - 我在 c++03 中的无锁循环队列有什么问题?
- python - 卷积中的通道优先与通道最后