Is there a better way to determine elapsed time in Perl?

前端 未结 4 1547
囚心锁ツ
囚心锁ツ 2021-02-01 12:47
my $start_time = [Time::HiRes::gettimeofday()];
my $diff = Time::HiRes::tv_interval($start_time);

print \"\\n\\n$diff\\n\";
4条回答
  •  爱一瞬间的悲伤
    2021-02-01 13:41

    Depends on what you are doing. If you want to measure wall clock time (the amount of actual time that has elapsed) you can't get much better. If you want to measure how long the computer has been doing something then you might want to look at the times function or the time command. The times function in Perl returns a list of the current accumulated time for this process in your code and the code of any modules you are using, this process in system calls, all of this process's children in user code, and all of this process's children in system calls.

    #!/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";
    

    The time command in UNIX is similar in function. You run a command like this

    time ./script.pl
    

    and it outputs something like this

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

    where real is the wall clock time and user and sys are the same as user and system above.

    The time command is easier for a human to use, but the times function gives you more information and is easier to fit into a computer program (plus it has the benefit of producing results while a program is still running).

    Oh, I forgot to mention $^T. This variable holds the start time of the program in seconds since the epoch, so if you only care about a granularity of seconds you can just say

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

    near the top of your program.

提交回复
热议问题