create function to normalize cpu usage width

This commit is contained in:
Iago Tito Oliveira 2021-03-27 15:41:07 -03:00
parent 8d1a7fa41b
commit 698cbc2191

View file

@ -14,12 +14,24 @@ get_tmux_option() {
fi fi
} }
# normalize the percentage string to always have a length of 5
normalize_percent_len() {
# the max length that the percent can reach, which happens for a two digit number with a decimal house: "99.9%"
max_len=5
percent_len=${#1}
let diff_len=$max_len-$percent_len
# if the diff_len is even, left will have 1 more space than right
let left_spaces=($diff_len+1)/2
let right_spaces=($diff_len)/2
printf "%${left_spaces}s%s%${right_spaces}s\n" "" $1 ""
}
get_percent() get_percent()
{ {
case $(uname -s) in case $(uname -s) in
Linux) Linux)
percent=$(LC_NUMERIC=en_US.UTF-8 top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}') percent=$(LC_NUMERIC=en_US.UTF-8 top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}')
echo $percent normalize_percent_len $percent
;; ;;
Darwin) Darwin)
@ -27,7 +39,7 @@ get_percent()
cpucores=$(sysctl -n hw.logicalcpu) cpucores=$(sysctl -n hw.logicalcpu)
cpuusage=$(( cpuvalue / cpucores )) cpuusage=$(( cpuvalue / cpucores ))
percent="$cpuusage%" percent="$cpuusage%"
echo $percent normalize_percent_len $percent
;; ;;
CYGWIN*|MINGW32*|MSYS*|MINGW*) CYGWIN*|MINGW32*|MSYS*|MINGW*)