i want use python to get the cpu_freq value from raspberry pi 4B
def GetCpuInfo():
# Get CPU frequence
cpu_freq =open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq").read()
return cpu_freq
when i print the cpu_freq data, the output always fixed in 1800000(it's the max cpu frequence 1.8Ghz of raspberry pi),but when each time i use the
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
this command in terminal,it give me the dynamic valve(600000-1800000) So why do i get wrong value when using the python? is it a wrong way to read this file?
CodePudding user response:
There's nothing wrong with your read()
.
The very act of starting Python can itself take enough cycles to cause the CPU to ramp up to full frequency, especially on a small system like a Pi.
To prevent that, add a delay to let it spool back down before you take your readings. For example:
import time
def GetCpuInfo():
with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") as f:
return f.read()
for _ in range(20):
time.sleep(1)
print(GetCpuInfo())