Created
September 5, 2016 16:32
-
-
Save ssaavedra/983f4bd4e660dd6683ca020dc5bf203c to your computer and use it in GitHub Desktop.
Get the CPU usage as a percentage. Great for use inside byobu/tmux, but can be used standalone.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# 5_cpu_percent: get the global CPU usage as a percentage | |
# | |
# Copyright (C) 2016 Santiago Saavedra | |
# | |
# Authors: Santiago Saavedra <santiagosaavedra@gmail.com> | |
# | |
# This program is free software: you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation, version 3 of the License. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program. If not, see <http://www.gnu.org/licenses/>. | |
self=$(basename $0) | |
mycache="$BYOBU_RUN_DIR/cache.$BYOBU_BACKEND/custom.$self.current" | |
touch "$mycache" | |
## By reading and continuing we are changing the value | |
_nice=x | |
_sys= | |
_idle= | |
_user= | |
_iowait= | |
_irq= | |
_softirq= | |
_steal= | |
_guest= | |
_guest_nice= | |
get_current_usage () { | |
grep 'cpu ' /proc/stat | |
} | |
CURRENT_USAGE=$(get_current_usage) | |
get_cpu_diff () { | |
local bogus user nice system idle iowait irq softirq steal guest guest_nice | |
read bogus user nice system idle iowait irq softirq steal guest guest_nice <<EOF | |
$1 | |
EOF | |
local prev_idle=$((idle + iowait)) | |
local prev_nonidle=$((user + nice + system + irq + softirq + steal)) | |
local prev_total=$((prev_idle + prev_nonidle)) | |
read bogus user nice system idle iowait irq softirq steal guest guest_nice <<EOF | |
$2 | |
EOF | |
local cur_idle=$((idle + iowait)) | |
local cur_nonidle=$((user + nice + system + irq + softirq + steal)) | |
local cur_total=$((cur_idle + cur_nonidle)) | |
local total_diff=$((cur_total - prev_total)) | |
local idle_diff=$((cur_idle - prev_idle)) | |
echo -n "" | |
local pct=$(echo "scale=2; ($total_diff - $idle_diff) / $total_diff * 100" | bc) | |
echo "$pct%% " | |
} | |
next_cpu_bar () { | |
echo "$CURRENT_USAGE" > "$mycache" | |
} | |
last_cpu_bar () { | |
local last=$(< "$mycache") | |
local now="$CURRENT_USAGE" | |
get_cpu_diff "$last" "$now" | |
} | |
last_cpu_bar | |
next_cpu_bar | |
# vi: syntax=sh ts=4 noexpandtab |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment