linux - 计算bash中每个进程的CPU使用率%

标签 linux bash process

我正在计算每个进程的 CPU 使用率百分比,我用这个脚本来完成:

#!/bin/bash

function getTotalTime() {
    echo $(awk '{print $14+$15}' /proc/${1}/stat)
}

function getStartTime() {
    echo $(awk '{print $22}' /proc/${1}/stat)
}

function getActualCPUTime() {
    echo $(cat /proc/stat | awk '/cpu / {for(i=1;i<=7;++i) sum+=$i; print sum}')
}

pidArray=($(ls -l /proc | awk '$9 ~/^[0-9]+/ {print $9}'))
let index=0

for i in ${!pidArray[*]}
do
    if [ ! -z ${pidArray[$i]} ] && [ -e "/proc/${pidArray[$i]}/stat" ]
    then
        cpuP[$index]=$(getTotalTime ${pidArray[$i]})
        let index+=1
    fi
done

cpuT=$(getActualCPUTime)
sleep 1
#hz=$(getconf CLK_TCK)
cpuT=$((($(getActualCPUTime)-$cpuT)))
#uptime=$(cat /proc/uptime | awk '{print $1}')

let index=0
for i in ${!pidArray[*]}
do
    if [ ! -z ${pidArray[$i]} ] && [ -e "/proc/${pidArray[$i]}/stat" ]
    then        
        #aux=$(($(getTotalTime ${pidArray[$i]})-${cpuP[$index]}))
        #echo "$aux ->  $cpuT"
        cpuP[$index]=$((100*($(getTotalTime ${pidArray[$i]})-${cpuP[$index]})/$cpuT))


        echo ${cpuP[$index]}
        let index+=1 
    fi  
done

为了测试,我开始一两次 cat/dev/zero >/dev/null 让一些进程使用 CPU,但是当我运行我的脚本并检查我看到的 % ~150 如果我运行其中一个进程或两个 ~90% 如果运行两个。

我认为这与/proc/stat/proc/PID/stat的单位有关,但我想不通。

有什么线索吗?

谢谢

最佳答案

我设法解决了它,问题是读取值的顺序。

在阅读之前

进程,cpu, sleep ,cpu,进程

正确的做法是

cpu,processes,sleep,cpu,processes

这就是为什么 cpu 值太小而我在某些进程中获得 150+% 的原因。

关于linux - 计算bash中每个进程的CPU使用率%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709869/

相关文章:

multithreading - 如何在aix上查看正在运行的进程的所有线程堆栈?

regex - 使用 sed 时缺少空格

python - 平均时间和 CPU Linux

linux - 确定使用最大内存量 (RAM) 的进程?

algorithm - 我的流程/脚本如何避免陷入无限循环?

bash - bash 命令 "rm *~"有什么作用?

linux - Putty 搜索 - 字符串后跟一个但不是两个符号

linux - Bash 在行尾添加不起作用

c++ - 线程在 pthread_rwlock_t 中挂起

bash - passwd:当我运行我创建的 Bash 脚本时,Debian 上出现无法识别的选项 '--stdin' 错误