Enhance CPU usage script to display real-time usage with continuous updates

This commit is contained in:
2025-04-01 10:26:46 +01:00
parent 2d8e749703
commit b5344fb9ea

View File

@@ -1,26 +1,28 @@
#!/bin/sh #!/bin/sh
# Script to display CPU usage
# Module showing overall CPU usage as a percentage.
# Cache in tmpfs to improve speed and reduce SSD load # Cache in tmpfs to improve speed and reduce SSD load
cache=/tmp/cpubarscache cache=/tmp/cpu-script-cache
rm /tmp/cpu-script-cache 2>/dev/null
# Extract CPU stats (total time and idle time) while true; do
cpu_stats=$(awk '/^cpu / {print $2 + $3 + $4 + $5, $5}' /proc/stat) sleep 1
cpu_stats=$(awk '/^cpu / {print $2 + $3 + $4 + $5, $5}' /proc/stat)
# Check if cache exists, if not, initialize it if [ ! -f "$cache" ]; then
[ ! -f $cache ] && echo "$cpu_stats" > "$cache" printf "  ---%% \r"
echo "$cpu_stats" >"$cache"
# Read previous CPU stats from cache continue
prev_stats=$(cat "$cache") fi
prev_stats=$(cat "$cache")
# Calculate CPU usage percentage and exit immediately echo "$cpu_stats $prev_stats" | awk '{
echo "$cpu_stats $prev_stats" | awk '{
total_diff = $1 - $3 total_diff = $1 - $3
idle_diff = $2 - $4 idle_diff = $2 - $4
usage = 100 * (1 - idle_diff / total_diff) if (total_diff == 0) {
printf " %.1f%%\n", usage usage = 0
exit # Terminate script after printing the first line } else {
usage = 100 * (1 - idle_diff / total_diff)
}
printf "  %.1f%% \r", usage
exit
}' }'
echo "$cpu_stats" >"$cache"
# Update cache with current stats done
echo "$cpu_stats" > "$cache"