【问题标题】:Calculate average of the printed time in a log file with Linux commands (or python)?使用 Linux 命令(或 python)计算日志文件中打印时间的平均值?
【发布时间】:2021-02-09 07:19:06
【问题描述】:

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

[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 快速获取此数字?谢谢。

【问题讨论】:

  • 没有“Linux 命令”这样的东西。为您的任务选择一个工具集。现在,我建议只使用 Python,因为它比大多数 shell 更干净,而且更通用。
  • 其他单位的时间也可以吗?分钟、小时等,还是只有几秒钟?

标签: python linux command-line


【解决方案1】:

这是一个使用正则表达式的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")

【讨论】:

  • 社区鼓励在代码中添加解释,而不是纯粹基于代码的答案(参见here
【解决方案2】:
sum=0
cnt=0
for log in logs:
  if "Estimate the time" in log:
    sum += extractSecondFromLog()
    cnt += 1
print(sum/cnt)

【讨论】:

  • sum 是内置函数,不要用作名字
【解决方案3】:
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

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2018-01-29
    • 2013-01-14
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    相关资源
    最近更新 更多