http://qs321.pair.com?node_id=35320


in reply to How can I keep track of the execution time of a script?

$^T is the time that the script started. So end your script by returning time()-$^T. You might want to put this in the sig die handler:
# your script goes here BEGIN { $SIG{__DIE__} = sub { print + time() - $^T, $/, @_ } } print + time() - $^T, $/
That prints the run time of your script in seconds.

Update: By the way, there is a module called Benchmark that is great for testing algorithms and routines and such. Turnstep wrote a great tutorial on it called Benchmarking Your Code

Update: For a variety of reasons, it is much better (and simpler too!) to use a single END block instead of the repition that I suggested. Thanks merlyn for pointing this out. (I also like the use of warn)

Also, If your script is taking longer then a minute or two, you might want to break down those seconds to be minutes:seconds, but don't forget the more work you do after that last call to time, the less accurate the stamp. (Well, time only has a granularity of a second... so you actually have plenty of room, but anyway...)

END { $a=time-$^T, warn sprintf "Runtime %d min %d sec\n", $a/60, $a%6 +0 }

Replies are listed 'Best First'.
RE: RE: How can I keep track of the execution time of a script?
by merlyn (Sage) on Oct 04, 2000 at 23:47 UTC
    Perhaps you wanted an END block instead of a DIE handler.
    END { warn "this script took ", time - $^T, " seconds\n"; }
    A die handler is only triggered on aborts. END blocks are triggered on all normal terminations, including aborts.

    -- Randal L. Schwartz, Perl hacker

      Good call... I forgot about the END block.
RE: RE: How can I keep track of the execution time of a script?
by Sarcasmo (Initiate) on Oct 05, 2000 at 00:28 UTC
    Thanks. That works nicely. How can I get that in milliseconds?

      There is a module that can get you high resoltion time stamps: Time::HiRes

      You should be able to take it from there.

      If you're running this script in Windows you can use the Win32::GetTickCount to get the time in miliseconds I would do something like this:
      BEGIN { $ms = Win32::GetTickCount(); } END { warn 'This script took ',Win32::GetTickCount() - $ms,'miliseconds'; }
        This has several flaws. First, the tick count is not milliseconds. Second, that count could roll in the middle of your execution, yeilding a negative run time. (this happens roughly once a month) Also, it's OS dependant.

        I asked Sarcasmo what OS this was for, and the answer is Linux.