进程输出的总时间(重击)

时间:2019-03-22 10:52:05

标签: bash time

我制作了一个脚本,用于测量某些进程的时间。这是我得到的文件:

real    0m6.768s
real    0m5.719s
real    0m5.173s
real    0m4.245s
real    0m5.257s
real    0m5.479s
real    0m6.446s
real    0m5.418s
real    0m5.654s

我用来获取时间的命令是这样的:

{ time my-command } |& grep real >> times.txt

我需要的是总结所有这些时间,并使用bash脚本得到多少分钟(如果适用的话)。

2 个答案:

答案 0 :(得分:1)

man bash开始,如果PAGER小于/ time

  If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its  exe-
  cution  are reported when the pipeline terminates.  The -p option changes the output format to that specified by
  POSIX.  The TIMEFORMAT variable may be set to a format string that specifies how the timing  information  should
   be displayed; see the description of TIMEFORMAT under Shell Variables below.

然后/TIMEFORMAT

         The  optional  l  specifies  a  longer  format, including minutes, of the form MMmSS.FFs.  The value of p
         determines whether or not the fraction is included.


         If this variable is not set, bash acts as if it had the value  $'\nreal\t%3lR\nuser\t%3lU\nsys%3lS'.   If
         the  value  is  null,  no  timing  information is displayed.  A trailing newline is added when the format
         string is displayed.

如果可以将其更改为类似的内容

TIMEFORMAT=$'\nreal\t%3R'

如果没有l,则求和可能会更容易。

请注意,格式也可能取决于语言环境LANG

比较

(LANG=fr_FR.UTF-8; time sleep 1)

(LANG=C; time sleep 1)

在这种情况下,可以使用awk

这样的外部工具来完成总和
awk '/^real/ {sum+=$2} END{print sum} ' times.txt

或perl

perl -aln -e '$sum+=$F[1] if /^real/; END{print $sum}' times.txt

答案 1 :(得分:0)

将输出放置到此命令

grep real | awk '{ gsub("m","*60+",$2); gsub("s","+",$2); printf("%s",$2); } END { printf("0\n"); }' | bc

如果您使用内置时间命令生成了输出,则此方法应该起作用。输出以秒为单位。