这是一个脚本,用于显示当前登录的每个用户的总 CPU使用率, showPerUserCPU.sh:
own=$(id -nu)
cpus=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
for user in $(who | awk '{print $1}' | sort -u)
do
# 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 { print user, sum, sum/CPUS; }') &
# don't spawn too many processes in parallel
sleep 0.05
done
wait
# 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; }'
这是一个稍作修改的版本,用于打印所有可用用户的CPU使用率(但跳过CPU使用率为零的用户), showAllPerUserCPU.sh:
own=$(id -nu)
cpus=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
for user in $(getent passwd | awk -F ":" '{print $1}' | sort -u)
do
# 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
done
wait
# 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; }'
第一列代表用户名,第二列代表合计CPU使用量,第三列代表根据CPU内核数进行标准化的CPU使用量。
还有一个相关的脚本可显示每个用户的总内存使用量: showPerUserMem.sh
对于实时监控,只需通过 watch
命令。
要按CPU使用率进行排序,请将输出传递给sort -k2 -nr
。
top -u user
将结果重定向到文件,然后监视另一个用户。然后,您将在给定的时间间隔内监视用户的proc使用情况。