【问题标题】:Is there a better way to determine elapsed time in Perl?有没有更好的方法来确定 Perl 中经过的时间?
【发布时间】:2009-03-18 00:24:43
【问题描述】:
my $start_time = [Time::HiRes::gettimeofday()];
my $diff = Time::HiRes::tv_interval($start_time);

print "\n\n$diff\n";

【问题讨论】:

    标签: perl time


    【解决方案1】:

    可能。取决于您所说的“更好”。

    如果您要求在功能方面“更好”的解决方案,那就差不多了。

    如果您要求一个“更好”的在“不那么尴尬”的符号的意义上,那么要知道,在标量上下文中,Time::HiRes::gettimeofday() 将返回自纪元以来的浮点秒数(带有小数代表微秒的部分),就像Time::HiRes::time()(这是标准time()函数的一个很好的替代品。)

    my $start_time = Time::HiRes::gettimeofday();
    ...
    my $stop_time = Time::HiRes::gettimeofday();
    printf("%.2f\n", $stop_time - $start_time);
    

    或:

    use Time::HiRes qw( time );
    
    my $begin_time = time();
    ...
    my $end_time = time();
    printf("%.2f\n", $end_time - $begin_time);
    

    【讨论】:

    • 未定义子程序 &Time::HiRes::
    【解决方案2】:

    取决于你在做什么。如果你想测量挂钟时间(已经过去的实际时间量),你就再好不过了。如果您想测量计算机执行某项操作的时间,您可能需要查看times 函数或time 命令。 Perl 中的times 函数返回您的代码中此进程的当前累积时间列表以及您正在使用的任何模块的代码、系统调用中的此进程、用户代码中此进程的所有子进程以及所有这些系统调用中进程的子进程。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use Time::HiRes;
    
    my $start_time = [Time::HiRes::gettimeofday()];
    .
    .
    .
    my ($user, $system, $child_user, $child_system) = times;
    print "wall clock time was ", Time::HiRes::tv_interval($start_time), "\n",
        "user time for $$ was $user\n",
        "system time for $$ was $system\n",
        "user time for all children was $child_user\n",
        "system time for all children was $child_system\n";
    

    UNIX 中的time 命令功能类似。你运行这样的命令

    time ./script.pl
    

    它会输出类似这样的东西

    real    0m0.692s
    user    0m0.019s
    sys     0m0.109s
    

    real 是挂钟时间,user 和 sys 与上面的 user 和 system 相同。

    time 命令对人类来说更容易使用,但times 函数可以为您提供更多信息,并且更容易融入计算机程序(此外,它还具有在程序仍在运行时产生结果的好处)。

    哦,我忘了提到$^T。这个变量以秒为单位保存程序的启动时间,所​​以如果你只关心秒的粒度,你可以说

    END { print "The program ran for ", time() - $^T, " seconds\n" }
    

    靠近程序顶部。

    【讨论】:

      【解决方案3】:

      差不多就是这样 - 这将为您提供高分辨率的经过时间。当然,除非有人弄乱了系统时钟。

      【讨论】:

        【解决方案4】:

        这对于服务中的计时很有用,粒度为一秒:

        开始...

        $debugtimer = time;
        $debugstr = "";
        

        ...任何你喜欢的地方...

        kerchunk("message") # message is short description of location in code
        

        ...程序结束...

        print "timings: $debugstr";
        

        ...和你的潜艇:

        sub kerchunk
        {
            my ($msg) = shift;
            my $pertock = time;
            my $kch = abs($debugtimer - $pertock);
            $debugstr .= "Elapsed at $msg: $kch<br>\n";
        }
        

        【讨论】:

          猜你喜欢
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 2019-09-03
          • 2011-01-28
          • 1970-01-01
          • 1970-01-01
          • 2018-06-29
          • 1970-01-01
          相关资源
          最近更新 更多