【问题标题】:storing the output of time in a variable将时间输出存储在变量中
【发布时间】:2015-05-03 06:52:18
【问题描述】:

我有以下命令行:

time `while [ $i -lt 200000 ]; do i=$[$i+1]; done` | grep "real"

根据我对 bash 的了解,这应该首先给我 while 循环的运行时间并将其用作grep 命令的输入,然后grep 命令应该只打印出由time 命令,而是打印time 命令的完整输出

那么为什么它没有像我预期的那样工作。还有更好的方法吗?

【问题讨论】:

  • 顺便说一句:不要将命令时间放在反引号中。 time 的特别之处(shell 关键字)是它允许您指定一个命令行来按原样 进行计时——甚至是一个整个管道。确实,这就是问题的根源:grep 命令成为计时的一部分。

标签: bash


【解决方案1】:

bash-builtin time 命令在 bash 中有点特殊。事实上,它被归类为关键字(尝试运行type time)。

它在 stderr 上打印它的输出,但是通过某种神奇的 bash 类型的“提升”输出在其包含的管道之外,所以即使你通过管道从命令中传输 stderr,它也不会通过。

您需要做的是将time 命令包围在一个支撑块中(这会导致time 的输出成为块的stderr 流的一部分),通过管道重定向块的stderr,然后你'会有time 输出:

{ time while [ $i -lt 200000 ]; do i=$[$i+1]; done; } 2>&1| grep real;

【讨论】:

    【解决方案2】:

    你需要从time捕获stderr:

    $ i=0; { time while [ "$i" -lt 200000 ]; do i=$[$i+1]; done; } 2>&1 | grep "real"
    real    0m2.799s
    

    讨论

    shell 关键字time 对整个管道进行操作,并在stderr 上报告时序信息。要捕获该输出,必须将time 放入组{...;} 或子shell (...),然后从该列表或子shell 中收集stderr。

    文档

    man bash 解释管道语法如下:

       Pipelines
           A  pipeline  is  a  sequence  of one or more commands separated by one of the control operators | or |&.  The format for a
           pipeline is:
    
                  [time [-p]] [ ! ] command [ [|⎪|&] command2 ... ]
    
       ...
    
       If  the  time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are
       reported when the pipeline terminates.
    

    【讨论】:

    • @mklement0 感谢您的关注。我更新了答案。
    【解决方案3】:

    真的,您的grep 不是一个好主意。 Bash 有一个很棒的 time 关键字,您可以根据需要格式化它的输出。

    在你的情况下,我会这样做:

    TIMEFORMAT=$'real\t%3lR'
    i=0
    time while [ "$i" -lt 200000 ]; do i=$[$i+1]; done
    

    请参阅 Bash Variables section 中的 TIMEFORMAT 规范。


    现在,您的命令显示了古老的 shell 技术。在现代 Bash 中,您的 while 循环将写为:

    while ((i<200000)); do ((++i)); done
    

    关于time关键字,你也可以看看这个问题:Parsing the output of Bash's time builtin

    【讨论】:

    • 干得好;从来不知道TIMEFORMAT;手册预览(无格式修饰符):%R 是实际经过的时间,%U 是在用户模式下花费的时间,%S 是在系统模式下花费的时间。 %P 报告 CPU 百分比。格式修饰符:0 到 3 之间的数字确定小数位,l 显示分钟和(小数)秒(而不仅仅是秒)。鉴于%R 大概包括服务其他进程所花费的时间,有没有一种简单的方法可以获取just bash 命令所花费的总时间?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2018-01-27
    • 2023-02-13
    相关资源
    最近更新 更多