【问题标题】:bash time output processingbash 时间输出处理
【发布时间】:2011-11-29 09:25:00
【问题描述】:

我知道time 会将计时统计输出发送到stderr。但不知何故,我无法在 bash 脚本或通过重定向将其捕获到文件中:

time $cmd 1>/dev/null 2>file
$output=`cat file`

或者

$output=`time $cmd 1>/dev/null`

我只对时间感兴趣,而不是命令的直接输出。我在这里阅读了一些帖子,但仍然没有找到可行的解决方案。有什么建议吗?

谢谢!

【问题讨论】:

    标签: bash time io


    【解决方案1】:

    试试:

    (time $cmd) 1>/dev/null 2>file
    

    这样(time $cmd) 在子shell 环境中执行,然后您可以重定向其输出。

    【讨论】:

    • 最好说(time $cmd 2>/dev/null 1>&2) 2>captured,这样命令中的stderr也会被丢弃。
    【解决方案2】:

    (使用 GNU 时间 /usr/bin/time 而不是 bash 内置)(感谢 @Michael Krelin)
    (或调用\time)(谢谢@Sorpigal,如果我知道这一点我会完全忘记)

    如何使用-o-a 命令行选项:

    -o FILE, --output=FILE
          Do not send the results to stderr, but overwrite the specified file.
    
    -a, --append
          (Used together with -o.) Do not overwrite but append.
    

    【讨论】:

    • 对两者都投了赞成票,但我想补充一下,您需要使用时间二进制文件的完整路径或 "time" 引用以使其使用可执行文件而不是内置 bash。
    • +1,但请注意,您可以只说\time 来调用可执行版本。
    【解决方案3】:

    我有一个类似的问题,我想进行优化。这个想法是多次运行程序,然后输出运行持续时间的统计信息。

    我使用了以下命令行:

    第一次运行: (time ./myprog)2>times.log

    下一次运行: (time ./myprog)2>>times.log

    请注意,我的 (bash?) 内置 time 以以下形式输出统计信息:

        real    0m2.548s
        user    0m7.341s
        sys     0m0.007s
    

    然后我运行以下 Perl 脚本来检索统计信息:

        #!/usr/bin/perl -w
    
        open FH, './times.log' or die "ERROR: ", $!;
    
        my $useracc1 = 0;
        my $useracc2 = 0;
        my $usermean = 0;
        my $uservar = 0;
        my $temp = 0;
    
        while(<FH>)
        {
            if("$_" =~ /user/)
            {
                if("$_" =~ /(\d+)m(\d{1,2})\.(\d{3})s/)
                {
                    $usercpt++;
                    $temp = $1*60 + $2 + $3*0.001;
                    $useracc1 += $temp;
                    $useracc2 += $temp**2;
                }
            }
        }
    
        if($usercpt ne 0)
        {
            $usermean = $useracc1 / $usercpt;
            $userdev = sqrt($useracc2 / $usercpt - $usermean**2);
            $usermean = int($usermean*1000)/1000;
            $userdev = int($userdev*1000)/1000;
        }
        else
        {
            $usermean = "---";
            $userdev = "---";
        }
    
        print "User: ", $usercpt, " runs, avg. ", $usermean, "s, std.dev. ", $userdev,"s\n";
    

    当然,正则表达式可能需要根据您的time 输出格式进行调整。它也可以很容易地扩展到包括真实和系统统计数据。

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 1970-01-01
      • 2021-02-18
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多