I would like to write a shellscript that reads the current CPU utilisation on a per-core basis. Is it possible to read this from the /sys
directory in Linux (CentOS 8)? I have found /sys/bus/cpu/drivers/processor/cpu0
which does give me a fair bit of information (like current frequency), but I’ve yet to figure out how to read CPU utilisation.
In other words: Is there a file that gives me current utilisation of a specific CPU core in Linux, specifically CentOS 8?
Advertisement
Answer
I believe that you should be able to extract information from /proc/stat – the lines that start with cpu$N, where $N is 0, 1, 2, …… For example:
Strongly suggesting reading articles referenced on other answer.
cpu0 101840 1 92875 80508446 4038 0 4562 0 0 0 cpu1 81264 0 68829 80842548 4424 0 2902 0 0 0
Repeated call will show larger values:
cpu 183357 1 162020 161382289 8463 0 7470 0 0 0 cpu0 102003 1 93061 80523961 4038 0 4565 0 0 0 cpu1 81354 0 68958 80858328 4424 0 2905 0 0 0
Notice CPU0 5th column (idle count) moving from 80508446 to 80523961
Format of each line in
cpuN user-time nice-time system-time idle-time io-wait ireq softirq steal guest guest_nice
So a basic solution:
while true ; for each cpu read current counters, at least user-time system-time and idle usage = current(user-time + system-time) - prev(user-time+system-time) idle = current(idle) - prev(idle) utilization = usage/(usage+idle) // print or whatever. set prev=current done