【问题标题】:How to Increment timestamps in text file如何增加文本文件中的时间戳
【发布时间】:2018-06-13 11:57:24
【问题描述】:

我正在比较两个除了时间戳之外完全相同的长日志文件。

例如:Log1

fn1-start 11:10:10
fn2-start 11:10:12
fn2-end   11:10:19
fn1-end   11:11:20
...
A long list
...

日志 2

fn1-start 11:22:11
fn2-start 11:22:13
fn2-end   11:22:20
fn1-end   11:23:41
...
A long list
...

我想使用一些比较工具来比较两个这样的日志文件,以找出导致性能下降的函数。

我想要的是增加或减少其中一个日志文件中的所有时间戳。第二个文件的时间戳从 11:22:11 开始,在我的情况下,我可以将 00:10:01 添加到第一个日志文件时间戳并比较日志。

因此,将 log 1 时间戳增加 00:12:01。 所以日志 1 现在是:

fn1-start 11:22:11
fn2-start 11:22:13
fn2-end   11:22:20
fn1-end   11:23:21
...
A long list
...

在这种情况下,fn1 在日志 2 中调用 fn2 函数后需要多花 20 秒才能完成。

我怎样才能做到这一点?我应该使用哪些工具?有什么替代方法吗?

【问题讨论】:

  • 欢迎来到 SO,您能否在 CODE TAGS 的帖子中添加更多示例输入和示例输出。
  • 为什么不在比较之前从文件中删除时间戳?
  • 看看gawk时间函数,尤其是mktime
  • @RavinderSingh13 我已经添加了代码示例。 glennjackman 然后没有什么可比较的,因为两个日志除了时间戳之外具有相同的内容。 kvantour 我去看看 谢谢。

标签: awk timestamp notepad++ text-manipulation


【解决方案1】:

因此,您希望比较各个函数的运行时间,而不是偏移它们,以便第一个函数同时开始。

这意味着您需要在比较两个文件之前计算函数运行持续时间。这可以通过一个相当简单的 awk 脚本来完成:

function get_durations() {
  awk '
  BEGIN{
    # Split spaces and dashes
    FS="[ ]*|-"
  }

  /start/ {
    start[$1] = $3
  }

  /end/ {
    if($1 in start)
      end[$1] = $3
    else
      print "No corresponding \"start\" for function " $1 > "/dev/stderr"
  }

  # Function to convert timestamps into seconds using gnu coreutils date
  function timestamp_to_seconds(ts) {
    close(sprintf("date \"+%%s\" --date=\"%s\"", ts) | getline sec)
    return sec
  }
  END {
    for (x in start){
      if(end[x]){
        end_seconds = timestamp_to_seconds(end[x])
        start_seconds = timestamp_to_seconds(start[x])
        printf("%s %s\n", x, end_seconds - start_seconds)
      }
      else{
        printf("%s inf\n", x)
        print "No corresponding \"end\" for function " x > "/dev/stderr"
      }
    }
  }
  ' "${1}"
}

要比较持续时间,您可以使用 awk 数组以类似的方式进行:

function compare_durations() {
  gawk -P '
    BEGIN{
      print "function,file1_duration,file2_duration,12_difference"
    }
    f[$1] {
      printf("%s,%s,%s,%s\n",
        $1,
        $2,
        f[$1],
        ($2 == "inf" || f[$1] == "inf" ? "inf" : $2 - f[$1]))
    }
    !f[$1]{
      f[$1] = $2
    }
  ' "${1}" "${2}"
}

此函数将两个文件作为输入,并打印出一个包含两个文件比较的 csv。

最后你可以一起使用这些函数来比较文件:

compare_durations <(get_durations input1) <(get_durations input2) > summary.csv

此解决方案假定函数名称不重复,如果它们重复 重复您可以更改脚本为每个函数添加一个计数器。 脚本的时间复杂度是 O(n) 但它使用 O(n) 空间,所以 如果你有很长的日志,你应该找到另一种方法。

【讨论】:

    猜你喜欢
    • 2020-11-24
    • 2011-11-21
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2012-06-05
    • 2020-05-07
    相关资源
    最近更新 更多