用bash自己计算CPU和内存使用率

如果你不自己计算,最简单的办法就是去解析ps的输出(top的应该比较麻烦一些)。如果我们自己亲自来计算呢?

我写了下面这么个脚本,可以粗略计算。为了对照方便,我同时给出了以这两种方式获取的结果。比较有趣的是,我在测试的过程中发现ps有时给出的CPU占用率结果竟然是101%!没看源代码,不知道它是怎么计算的……

BTW:无意间发现还有个dstat,貌似很酷~~8-)

[bash]

!/bin/bash

if [ $# -gt 0 ] ;
then
pid=$1
if [ ! -d /proc/${pid} ] ;
then
echo “No such process!”
exit 1
fi
else
pid=$$
fi
echo “the pid is: ${pid}”
tmp1=$(awk ‘/cpu /{print $2,$4;}’ /proc/stat)
tmp2=$(sed -e ‘s/(.*)//‘ /proc/${pid}/stat | awk ‘{print $13, $14;}’)
old_sys_stime=$(echo ${tmp1} | cut -d’ ‘ -f 2)
old_sys_utime=$(echo ${tmp1} | cut -d’ ‘ -f 1)
old_prc_stime=$(echo ${tmp2} | cut -d’ ‘ -f 2)
old_prc_utime=$(echo ${tmp2} | cut -d’ ‘ -f 1)

do some dummy stuffs

for((i=0;i /dev/null

echo “ps reported its cpu usage was: $(ps -o pcpu -p ${pid} | tail -n 1)%”

tmp1=$(awk ‘/cpu /{print $2,$4;}’ /proc/stat)
tmp2=$(sed -e ‘s/(.*)//‘ /proc/${pid}/stat | awk ‘{print $13, $14;}’)
new_sys_stime=$(echo ${tmp1} | cut -d’ ‘ -f 2)
new_sys_utime=$(echo ${tmp1} | cut -d’ ‘ -f 1)
new_prc_stime=$(echo ${tmp2} | cut -d’ ‘ -f 2)
new_prc_utime=$(echo ${tmp2} | cut -d’ ‘ -f 1)

echo -n “my calculation is:”
echo $(awk “BEGIN { print (($new_prc_stime - $old_prc_stime) + ($new_prc_utime -$old_prc_utime))/(($new_sys_stime - $old_sys_stime) + ($new_sys_utime -$old_sys_utime));}”)

#

echo “ps reported its memory usage was: $(ps -o pmem -p ${pid} | tail -n 1)%”
total=$(awk -F: ‘/MemTotal/{print $2}’ /proc/meminfo | sed -e ‘s/[^0-9]//g’)
mine=$(awk -F: ‘/VmRSS/{print $2}’ /proc/${pid}/status | sed -e ‘s/[^0-9]//g’)

echo -n “my calculation is:”
echo $(awk “BEGIN{print $mine/$total;}”)

exit 0
[/bash]