问题
I'm aware this question has been asked numerous times over but unfortunately none of the given answers seem to work for what I need.
Everyone seems to recommend /proc/stat
however I can't seem to find 1 answer that works as expected:
as you can see here, core 0 reports being 16% used even though it's actually only 3% used in fact it doesn't matter if it's 100%, it still reports 16% with only a 0.01%-0.02% increase
I've also tested another approach with only $2+$4 +$5
rather than the whole range, but even that returned inaccurate results...
How do CPU monitors, like the graph above, derive their information??
because it doesn't appear to be through /proc/stat
unless everyone's doing something wrong.
notable resources:
- Accurate calculation of CPU usage given in percentage in Linux?
- How to get overall CPU usage (e.g. 57%) on Linux
- https://devbest.com/threads/linux-scripting-with-xfce4-panels-generic-monitor-applet.89845/
I've looked through much more, but they all pretty much point to the same things.
As for the script, I know it's a bit messy, I don't work with bash much, but here it is:
#!/bin/bash
H=($(awk '/MHz/{printf "%.2fGHz|", $4/1000}' /proc/cpuinfo))
A=($(awk 'FNR>1 && FNR<4 {
i=$5+$6; printf "%d|%d\n", i, i+$2+$3+$4+$7+$8+$9
}' /proc/stat))
sleep 0.125
awk -v a="${A[*]}" -v h="${H[*]}" -v n="0" 'FNR>1 && FNR<4 {
n++
split(h,s,"|"); split(a,p,"|")
i=$5+$6; t=(i+$2+$3+$4+$7+$8+$9)-p[n,1]
printf "%s: %s %.2f%\n", $1, s[n], ((t-(i-p[n,0]))/t)*100
}' /proc/stat
pretty much all of it was followed from other answers...
If there's a better way to do any of this (such as merging cpuinfo
with stat
, or not needlessly splitting an array to prevent s[n]
from reporting a scalar error, or even sleeping and re-reading within awk), by all means please improve. :)
来源:https://stackoverflow.com/questions/60579935/how-can-i-display-an-accurate-calculation-of-cpu-use-in-percent