agustina_s has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perlmonks....

Is there any way to print/get time taken for a prog to run until it completes everything?

For eg I have quite a large program to filter out some database, and if the data base is large, it may takes sometimes to complete the job.So I want the program to print something like :

End of program. Takes 5 seconds to run.
At the end of the program.
Thanks in advanced.

Replies are listed 'Best First'.
Re: time taken for prog to finish..
by blakem (Monsignor) on Jan 25, 2002 at 13:15 UTC
    On unix machines you can use the time program (not to be confused with perls time function) to get this information....
    % time perl -e 'sleep 3' 0.01user 0.01system 0:03.02elapsed 0%CPU (0avgtext+0avgdata 0maxreside +nt)k 0inputs+0outputs (246major+28minor)pagefaults 0swaps
    If you look closely at this output you'll see that it took 3.02 seconds to run the program (in this case perl -e 'sleep 3')

    -Blake

      If you don't mind trading granularity for portability, you can make use of the magic variable $^T at the end of your script ...

      END { printf "Took %d seconds to run.\n", time - $^T; }

          --k.


        Hi... I have tried to put it in my prog:
        while(<>){ ..... } END { printf "Took %d seconds to run.\n", time - $^T; }
        Hm but when I compile it... it doesn't print out anything. I also try using the ";" after the last }. Thanks..
Re: time taken for prog to finish..
by seattlejohn (Deacon) on Jan 25, 2002 at 14:47 UTC
    The Benchmark module should do what you need. Ex:
    use Benchmark; my $start_time = new Benchmark; # do your processing my $end_time = new Benchmark; my $execution_time = timediff($end_time, $start_time); print timestr($execution_time);

    Sample output:

    4 wallclock secs ( 3.64 usr +  0.00 sys =  3.64 CPU)

    You could easily extract the information you need from this string.

    See perldoc benchmark for more info...

Re: time taken for prog to finish..
by screamingeagle (Curate) on Jan 25, 2002 at 13:33 UTC
    Hi,
    You could get the timestamp at the beginning of the perl script, and then get the timestamp at the end of the perl script, and then print out the difference (use the time function in Perl). If you need to measure the difference very accurately (i.e. less than one second), you can use the Time::HiRes module, or if you have gettimeofday(2), you may be able to use the syscall interface of Perl. Here's the link to the Perl FAQ which explains how to do it :
    PerlFAQ8
Re: time taken for prog to finish..
by MZSanford (Curate) on Jan 25, 2002 at 16:22 UTC
    I have used the use-time-at-the-begining-and-end mthod, as well as the $^T method.
    Personally, i like Benchmark for my personal code, but for production work, i tend to use the times function.
    from the frivolous to the serious