如何计算平均响应时间Bash脚本

时间:2020-01-12 11:04:31

标签: bash

我有一个bash脚本,该脚本从给定的日志中计算特定Java方法的响应时间。 该脚本由2个循环组成,一个循环遍历for (( i = 5; i > 0 ; i--))的最后5分钟,并标识了第二个循环所需的“ ID”,因此我可以匹配开始时间和结束时间。在第二个循环中,我正在计算diff = $(($endTime - $startTime)); echo $diff

现在,我想从最近5分钟的所有结果中获取平均响应时间。如果我叫脚本./responseTime.sh | awk '{sum+=$1} END {print sum / NR}',可以用awk轻松完成。 如何在不使用此管道的情况下计算平均值(我不知道它每运行5分钟将获得多少结果)?

我的本​​地计算机上没有这样的日志,无法向您显示其工作方式。这是我的剧本

#!/bin/bash

logfile=/var/log/examples.txt

#loop through last 5 min

  for (( i = 5; i >=0; i-- ))

    do

     debugDate=$(date --date="$i minutes ago" "+%b%d %H:%M")
     folderId=$(grep "$debugDate" $logfile  | sed -rn '/.*folderId:([^ ]*).*/ s//\1/p' ) # identify id's and store results

      for j in $folderId

       do

        startTime=$(grep "$j" $logfile | grep "Starting" | awk '{split ($2,Time,":"); print Time[1]*3600000+Time[2]*60000+Time[3]*1000}') #get the value in ms
        endTime=$(grep "$j" $logfile | grep "process finished" | awk '{split ($2,Time,":"); print Time[1]*3600000+Time[2]*60000+Time[3]*1000}')

      if [ ${#startTime} -ne 8 ] || [ ${#endTime} -ne 8 ] #exclude midnight results and retries

      then

         continue

      fi

       responseTime=$(($endTime - $startTime))
       echo $responseTime #test results

      done

  done
cat examples.txt

[Jan12 18:26:00] Initialized session for folderId:8005
[Jan12 18:26:15] Starting process [8005]
[Jan12 18:27:00] Initialized session for folderId:8004
[Jan12 18:27:17] Starting process [8004]
[Jan12 18:28:00] Initialized session for folderId:8003
[Jan12 18:28:16] Starting process [8003]
[Jan12 18:29:00] Initialized session for folderId:8002
[Jan12 18:29:15] Starting process [8002]
[Jan12 18:30:00] Initialized session for folderId:8001
[Jan12 18:30:12] Starting process [8001]
[Jan12 18:31:00] Initialized session for folderId:8000
[Jan12 18:31:16] Starting process [8000]
[Jan12 18:26:31] process finished [8005]
[Jan12 18:27:41] process finished [8004]
[Jan12 18:28:55] process finished [8003]
[Jan12 18:29:49] process finished [8002]
[Jan12 18:30:33] process finished [8001]
[Jan12 18:31:35] process finished [8000]

1 个答案:

答案 0 :(得分:2)

对于简单的数学运算,您可以使用bash内置函数。请注意,bash没有浮点数学运算,因此您将获得全秒分辨率的结果。

sum=0
count=0
for (( i = 5; i >=0; i-- ))
do
   ...
   Original Loop Here
   responseTime=$(($endTime - $startTime))
   echo $responseTime #test results
   ...
   # Update sum and count
   sum=$((sum+responseTime))
   count=$((count+1))   
done
# Print Average
[ "$count" -gt 0 ] && echo "Average: $((sum/count))"