微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Linux 命令或 python计算日志文件中打印时间的平均值?

如何解决使用 Linux 命令或 python计算日志文件中打印时间的平均值?

我有一个如下所示的日志文件

[info] Estimate the time: 2.7s
[info] Estimate some other time: 7.9s 
[info] Estimate the time: 5.6s
[debug] variable x uninitialized

我想计算“估计时间:”之后的平均时间,我在这种情况下 (2.7+5.6)/2=4.15

如何使用 Linux 命令或 python 快速获取此数字?谢谢。

解决方法

这是一个使用正则表达式的python脚本:

import re

# Open the file and get the data in a string
f = open('your_log','r')
text = f.read()

# Use regex to find the pattern
matches = re.findall(r'Estimate the time: (\d+\.\d+)s',text)
if matches:
    times = [float(time) for time in matches] # Convert str in float
    mean = sum(times) / len(times) # Calculate the mean with built-in methods
    print(mean)
else:
    print("no data")
,
sum=0
cnt=0
for log in logs:
  if "Estimate the time" in log:
    sum += extractSecondFromLog()
    cnt += 1
print(sum/cnt)
,
awk '/\[info\] Estimate the time:/ { map[cnt++]=+$5 } END { for (i in map) { cnt1++;tot=tot+map[i] } print tot/cnt1 }' logfile

说明:

awk '/\[info\] Estimate the time:/ {                # Process lines that contain "[info] Estimate the time:"
                 map[cnt++]=+$5                     # Create an array called map with an incrementing index and the 5th space delimited field as the value
               } 
           END {                                    # Process at the end of the file
                 for (i in map) { 
                    cnt1++;                         # Loop through the array and increment a counter with each iteration
                    tot=tot+map[i]                  # Create a running total variable
                 } 
                 print tot/cnt1                     # Print the running total divided by the count.
                }' logfile

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?