Skip to content

Instantly share code, notes, and snippets.

Created January 3, 2021 12:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GoingMyWay/8ac6026797a48d7cda1a727b16922a42 to your computer and use it in GitHub Desktop.
show per user CPU usage
# print total CPU usage in percent of all available users
# but skips the ones with a CPU usage of zero
# 1st column: user
# 2nd column: aggregated CPU usage
# 3rd column: normalized CPU usage according to the number of cores
# to sort by CPU usage, pipe the output to 'sort -k2 -nr'
set -e
own=$(id -nu)
cpus=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
for user in $(getent passwd | awk -F ":" '{print $1}' | sort -u)
# print other user's CPU usage in parallel but skip own one because
# spawning many processes will increase our CPU usage significantly
if [ "$user" = "$own" ]; then continue; fi
(top -b -n 1 -u "$user" | awk -v user=$user -v CPUS=$cpus 'NR>7 { sum += $9; } END { if (sum > 0.0) print user, sum, sum/CPUS; }') &
# don't spawn too many processes in parallel
sleep 0.05
# print own CPU usage after all spawned processes completed
top -b -n 1 -u "$own" | awk -v user=$own -v CPUS=$cpus 'NR>7 { sum += $9; } END { print user, sum, sum/CPUS; }'
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment