Linux性能统计工具

有时候测试后端服务需要监控该服务消耗的系统资源,这个时候就需要自己开发工具来满足性能统计需求了:

以下demo以收集某个服务消耗的系统cpu和内存为示例:

通过条件控制

#!/bin/bash
k=$1
if [ -z $k ]
then
        echo "need  a PID or process name as a argument!"
else
        count=`ps -ef | grep -c $k`
        #echo "进程数为:$count"
        if [ $count -lt 4 ]
        then
                echo "the PID or processs name $k is not exist!!"
        else
                top -n 20 -d 1 -b | grep  --line-buffered $k | awk 'BEGIN{OFS="\t";print "%CPU","%MEM"} {print $9,$10} {CPU+=$9;MEM+=$10} END{print ".........."; print "   avg"; print CPU/NR,MEM/NR}'
        fi
fi

或者结合函数调用: 

  1 #!/bin/bash
  2 function cpu_mem(){
  3 local proc=$1
  4 local duration=$2
  5 #判断是否有参数,没有就提醒追加pid或者进程名
  6 [ -z $proc ] && { echo "need a PID or process name as a argument!!please append the argument after the runing-script command~~";return 1; }
  7 #判断参数中是否带了监控时长,如果没有带监控时长参数,则使用系统默认时长10s
  8 [ -z $duration ] && duration=10
  9 echo "统计进程:$proc,监控时长:$duration秒!"
 10 
 11 top -n $duration -d 1 -b | grep -i --line-buffered $proc | awk 'BEGIN{OFS="\t";print "%CPU","%MEM"} {print $9,$10} {CPU+=$9;MEM+=$10} END{print "...........";print "     avg";print CPU/NR,MEM/NR}'
 12 
 13 }
 14 cpu_mem $1 $2

利用smem工具统计进程消耗内存PSS:Index of /smem/download

for i in {1..10};do smem | grep 27843 | awk 'NR==2{print $0}'| awk 'BEGIN{print "内存消耗"} {print $7}';sleep 2;done

扫描二维码关注公众号,回复: 13295807 查看本文章

 踩过的坑:bash脚本中的缩进空格一定要严格查看,不然很难发现报错信息...

猜你喜欢

转载自blog.csdn.net/qq_40132294/article/details/120545298