Monday, May 25, 2020

Python to check CPUs speed of Raspberry Pi

In Terminal, you can use this command to get the current CPU current frequency:

$ cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq

where cpu0 can be cpu0~3 for Raspberry Pi 4B. You can enter this command to get frequency of all 4 CPUs.

$ cat /sys/devices/system/cpu/cpu[0-3]/cpufreq/scaling_cur_freq


Here is my Python exercise to display speeds of CPUs on Raspberry Pi 4B. It's found that running this script will make the CPUs running in higher speed. For demonstration, I insert a delay and repeat read the CPUs speed to show the effect.


checkCPUs.py
import sys
import subprocess
import time

cmd = "cat /proc/device-tree/model"
model = subprocess.check_output(cmd, shell=True).decode("utf-8")
print(model)
print("Python: " + sys.version)
print()

def readCPUs():
    #cmd = "find /sys/devices/system/cpu/cpu[0-3]/cpufreq/scaling_cur_freq -type f | xargs cat"
    cmd = "cat /sys/devices/system/cpu/cpu[0-3]/cpufreq/scaling_cur_freq"
    freqs = subprocess.check_output(cmd, shell=True).decode("utf-8")
    freqList = freqs.splitlines()

    for index, i in enumerate(freqList):
        curFreq = float(i)
        print("CPU" + str(index) + " : " + str(curFreq/1000000) + " GHz")
        
time.sleep(3)
readCPUs()
readCPUs()
readCPUs()


No comments: