Linux与Shell实战之性能统计与自动化脚本

性能统计

统计阿里云盾进程的性能,每1s统计一次,统计他的cpu、mem的利用率,用tab隔开,并在最后空出一行打印下两个指标的平均值。

perf_avg(){
#todo
}


perf_avg 进程名字
3 20
2 30
1 25

avg:
2 25

自动化脚本

#!/bin/env bash

perf_avg ()
{
    top -b -d 1 -n 3 | grep --color=auto -i "$1" --line-buffered | awk '{c+=$9;n+=$10;print $9,$10}END{print ""; print "avg:" c/NR, n/NR}'
}

perf_avg "$2

PPT

perf_avg(){
top -b -d 1 -n 3|grep -i 'aliyundun$' --line-buffered |awk '{c+=$9;n+=$10;print $9,$10}END{print ""; print "avg:" c/NR, n/NR}'
}
1 个赞
perf_avg(){
    top -b -n 10 -d 1 -p $1 > testfile
    awk '{print $9,$10}' testfile
    echo "avg:"
    awk '{sum+=$9}{sum+=$10}END{print $9/NR,$10/NR}' testfile
}
@shell.ceshiren.com ~]$ perf_avg 2095
0.0 2.3
1.0 2.3
9.0 2.3
8.0 2.3
3.0 2.3
8.9 2.3
2.0 2.3
7.0 2.3
8.0 2.3
1.0 2.3
avg:
0.1 0.23
1 个赞

函数如下

perf_avg(){
    top -b -d 1 -n 3 | grep "AliYunDun$" | awk 'BEGIN{cpu_sum=0;mem_sum=0}{cpu_sum+=$9;mem_sum+=$10;print $9,$10}END{print "";print "avg:";print cpu_sum/NR,mem_sum/NR}'
}

执行结果图

>vim auto.sh
#!/bin/env bash 

perf_avg(){
top -b -d 1 -n 3|grep -i "$1" --line-buffered | awk '{c+=$9;n+=$10;print $9,$10}END{print "";print "avg:" c/NR, n/NR}'

}

perf_avg "$2"

>chmod +x  auto.sh

>auto arg1 Aliyundun

arg1 作为位置参数一没有实际传入;
Aliyundun 作为位置二参数传参perf_avg "$2" 的 $2,然后Aliyundun 作为位置一参数传入到函数"$1"处