The way you've shown is right. However, you may want to make a function from it, if you don't want to clutter the code with time calls.

Either do this:

use warnings; use strict; sub measure_time(&) { my($btime, $etime); $btime = time; &{$_[0]}(); $etime = time; warn "elapsed time was: ", $etime - $btime, " s\n"; } measure_time { sleep 60; }; __END__

Or, if you want to measure time in such a way that it doesn't line up with scopes, then do this:

use warnings; use strict; { my @btime; sub BEGIN_TIME { push @btime, time; } sub END_TIME { @btime or die "error: END_TIME without BEGIN_TIME"; my($btime, $etime) = (pop @btime, time); warn "elapsed time was ", $etime - $btime, " s\n"; } END { @btime and warn "warning: BEGIN_TIME without END_TIME"; } } sub foo { sleep 2; END_TIME; sleep 2; } BEGIN_TIME; sleep 3; foo(); __END__

Also see the timethis function in the Benchmark module. If you want to time the whole script, not just some parts of it, and you're on a unix-like system, use the time shell builtin or the time(1) program.


In reply to Re: Elapsed time in perl by ambrus
in thread Elapsed time in perl by nisha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.