为什么从 /sys/bus/... 读取需要这么多时间?
Why does reading from /sys/bus/... take so much time?
我正在从事一个需要来自温度传感器的传感器数据的项目。在使用 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上,它们的系统调用直接由注册处理major/minor数字对的特定驱动程序实现,因此它们的性能取决于operating-system 该驱动程序的实现。
高延迟是 w1-therm
驱动程序的常见问题;无论您使用何种编程语言,它都会发生。
根据硬件数据 sheet,在 https://www.maximintegrated.com/en/products/sensors/DS18B20.html,生成 12 位输出时刷新率约为 750 毫秒。因此,即使其他一切都绝对完美,您每次读取温度的时间大约为 3/4 秒。
坦率地说,在温度传感器的情况下,更快的刷新率没有意义——如果设备本身的物理温度变化如此之快,以至于您每秒需要的不仅仅是测量(考虑到热量实际传导到传感器所需的时间),你遇到了更大的问题。
我正在从事一个需要来自温度传感器的传感器数据的项目。在使用 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上,它们的系统调用直接由注册处理major/minor数字对的特定驱动程序实现,因此它们的性能取决于operating-system 该驱动程序的实现。
高延迟是 w1-therm
驱动程序的常见问题;无论您使用何种编程语言,它都会发生。
根据硬件数据 sheet,在 https://www.maximintegrated.com/en/products/sensors/DS18B20.html,生成 12 位输出时刷新率约为 750 毫秒。因此,即使其他一切都绝对完美,您每次读取温度的时间大约为 3/4 秒。
坦率地说,在温度传感器的情况下,更快的刷新率没有意义——如果设备本身的物理温度变化如此之快,以至于您每秒需要的不仅仅是测量(考虑到热量实际传导到传感器所需的时间),你遇到了更大的问题。