当前位置:网站首页>Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
2022-07-31 01:37:00 【爱吃 香菜】

最近在进行压测,为了观察并定位服务性能的瓶颈,所以在代码中很多地方加了执行耗时的日志,但这种方式只能观察,却在压测的时候,不太能准确的把握代码中某些方法的性能,所以想到写一个脚本,用来统计所加的日志中的平均耗时,最大耗时,最小耗时等等,这需要保证每行日志都是唯一的,代码中添加日志的方式如下:

为了便于验证,写了一个简单的日志文件 console.log ,内容如下:
[[email protected] shell]# cat console.log
filterStr 23
filterStr 56
filterStr 89
filterStr 1
filterStr 10
filterStr 2
requireTime 3
requireTime 4
requireTime 3
requireTime 10
1.先编写一个计算 含 filterStr 日志行的所有平均时间,最大时间,最小时间,脚本示例如下:
#!/bin/bash
sum=0
min=`cat console.log|grep "filterStr"|awk '{print $2}'|head -n 1`
max=0
for value in `cat console.log|grep 'filterStr'|awk '{print $2}'`
do
sum=$(($sum+$value))
if [ $value -le $min ];then
min=$value
fi
if [ $value -ge $max ];then
max=$value
fi
done
echo "总共耗时:"$sum
totalCount=`cat console.log|grep 'filterStr'|awk '{print $2}'|wc -l`
echo "总共请求次数为:"$totalCount
#计算请求的平均时间
avageTime=$(($sum/$totalCount))
echo "平均请求响应时间为: "$avageTime
#打印最大值与最小值
echo "最大值为:"$max
echo "最小值为:"$min
最小值的初始定义命令为: min=cat console.log|grep "filterStr"|awk '{print $2}'|head -n 1 ; 这行命令过滤出日志的所有行,并取第一行中过滤出的第二个值(awk ‘{print $2}’)。所以需要提前预定好 该耗时计算在日志中的位置,我这边示例中位于第二个位置,所以取第二个$2 的 值
该脚本执行效果如下:

2. 通过动态传参过滤内容的方式执行执行脚本
由于服务中加了很多位于不同代码处的耗时日志,所以想到通过动态传参的方式执行脚本,shell 脚本示例如下:
#!/bin/bash
sum=0
min=`cat console.log|grep "$filterStr"|awk '{print $2}'|head -n 1`
max=0
filterStr=$1
for value in `cat console.log|grep "$filterStr"|awk '{print $2}'`
do
sum=$(($sum+$value))
if [ $value -le $min ];then
min=$value
fi
if [ $value -ge $max ];then
max=$value
fi
done
echo "总共耗时:"$sum
totalCount=`cat console.log|grep "$filterStr"|awk '{print $2}'|wc -l`
echo "总共请求行数为:"$totalCount
#计算请求的平均时间
avageTime=$(($sum/$totalCount))
echo "平均请求响应时间为: "$avageTime
#打印最大值与最小值
echo "最大值为:"$max
echo "最小值为:"$min
用该脚本计算 console.log 中的 requireTime 相关行的耗时统计:

现在我邀请你进入我们的软件测试学习交流群:【746506216】,备注“入群”, 大家可以一起探讨交流软件测试,共同学习软件测试技术、面试等软件测试方方面面,还会有免费直播课,收获更多测试技巧,我们一起进阶Python自动化测试/测试开发,走向高薪之路。
喜欢软件测试的小伙伴们,如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一 键三连哦!
边栏推荐
猜你喜欢

System design. Short chain system design

prometheus 监控概述

Kyushu cloud as cloud computing standardization excellent member unit

297. 二叉树的序列化与反序列化

Overview of prometheus monitoring

《MySQL数据库进阶实战》读后感(SQL 小虚竹)

Xiaohei's leetcode journey: 104. The maximum depth of a binary tree

Word 表格跨页,仍然显示标题

MySQL的存储过程

【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)
随机推荐
权限管理怎么做的?
《MySQL数据库进阶实战》读后感(SQL 小虚竹)
Sping.事务的传播特性
221. 最大正方形
C语言_结构体指针数组函数选票系统
Parameter introduction and selection points of wireless module
JPEG Steganalysis of Digital Image Steganography
prometheus 监控概述
tensorflow与GPU版本对应安装问题
leetcode-399:除法求值
观察者(observer)模式(一)
计算S=a+aa+…+aa…a
射频器件的基本参数2
The difference between 4G communication module CAT1 and CAT4
网站频繁出现mysql等数据库连接失败等信息解决办法
软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?
Shell变量与赋值、变量运算、特殊变量
VS warning LNK4099:未找到 PDB 的解决方案
简易表白小页面
MySQL (6)