Skip to content

Instantly share code, notes, and snippets.

@peerasan
Created June 7, 2021 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peerasan/28bb1b62d3ac5d10918f7127028ee38a to your computer and use it in GitHub Desktop.
Save peerasan/28bb1b62d3ac5d10918f7127028ee38a to your computer and use it in GitHub Desktop.
Monitor CPU per Core
#!/bin/bash
function getCPU(){
LCPU=`grep "^processor" /proc/cpuinfo | sort -u | wc -l`
echo -n $LCPU-1
}
function getCpuUtilizationByCore(){
# Format: cpu<Number>
local CoreName="$1"
#cpu_util=<(grep $CoreName /proc/stat) <(sleep 1 && grep $CoreName /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}' #PERMISSION DENIED
cpu_util=$(awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1); }' <(grep $CoreName /proc/stat) <(sleep 1;grep $CoreName /proc/stat) | cut -d "." -f 1)
echo -n "${cpu_util}"
}
CPUcount=$(getCPU);
for (( i=0; i<=$CPUcount; i++ )) do
CoreUsage=$(getCpuUtilizationByCore "cpu$i")
echo "CPU Core $i : $CoreUsage";
done
#keyword: cpu, core, monitor, flamegraph, debug
# OUTPUT
# test with "stress --cpu 2"
CPU Core 0 : 100
CPU Core 1 : 42
CPU Core 2 : 2
CPU Core 3 : 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment