summaryrefslogtreecommitdiff
path: root/local/bin/sb-cpuusage
blob: c05576b5c27f3e7d379d2c8b5aebf4fe013358c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/bin/sh
#Display CPU usage percentage

_openbsd() {
	CPUS=$(sysctl | grep 'hw.ncpuonline' | sed 's/^.*=//')
	TOTALUSAGE=$(ps aux | awk '{print $3}' | sed '1d' | sort | paste -s -d+ - | bc)
	USAGE=$(printf "$TOTALUSAGE / $CPUS\n" | bc -l)
	printf "$USAGE" | grep "^\.[0-9]" > /dev/null && printf "0$(printf $USAGE | cut -c1-3)%%" || printf "$(printf "$USAGE" | cut -c1-4)%%\n"
}

_freebsd() {
	CPUS="$(sysctl hw.ncpu | sed 's/^.*: //')"
	FREE=$(ps -o %cpu -p $(pgrep -S idle) | tail -n 1)
	TPP=$(expr $CPUS \* 100)
	TOTALUSAGE=$(printf "$TPP - $FREE" | bc -l)
	USAGE=$(printf "$TOTALUSAGE / $CPUS" | bc -l | cut -c -4)
	printf "$USAGE" | egrep "\.[0-9]{3}" > /dev/null && printf "0$(printf $USAGE | cut -c -3)%%\n" || printf -- "$USAGE%%\n"
}

_linux() {
	TOTALUSAGE="$(ps axch -o cmd,%cpu --sort=-%cpu | sed 's/ //' | grep -E -o " [0-9].*" | sed 's/ //' | paste -s -d+ - | bc)"
	USAGE="$(printf "$(printf "$TOTALUSAGE / $(nproc)\n" | bc -l | cut -c1-4)%%\n")"
	printf -- "$USAGE%" | grep "^\.[0-9]" > /dev/null && printf -- "0$(printf -- $USAGE% | cut -c1-3)%%" || printf -- "$(printf -- "$USAGE%" | cut -c1-4)%%\n"
}

case $(uname) in
	Linux) _linux ;;
	OpenBSD) _openbsd  ;;
	FreeBSD) _freebsd ;;
esac