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

Hi Perl Monks

I'm trying to get the timestamp of subrotine before and after its execution and determine its duration.

Currently, I'm doing this:

$time_start = strftime("%H:%M:%S", localtime(time)); &my_rotine(); $time_end = strftime("%H:%M:%S", localtime(time)); $duration = $time_end - $time_start;

However, i get a warning:

Argument "13:13:13" isn't numeric in subtration.

But the result is:

Start = 13:13:13 ; End = 13:13:15 ; Duration = 2

Is there a better way to do this?

Replies are listed 'Best First'.
Re: Operations with strftime
by Corion (Patriarch) on Jun 17, 2014 at 11:06 UTC

    Strings do not work in subtraction.

    Maybe consider reading time to find out what the function returns. After that, it should be trivial to find out how to get the time taken.

    Update: ambrus found it for me - the most roundabout way to get an epoch timestamp would be

    strftime( '%s', localtime( time ))

    ... but that's just identical to time().

      FWIW, strftime is damn handy for date subtraction and addition if you don't want to use heavy weighted modules like DateTime. I've had great success with it, see for more information:

      How Do I Get Yesterday's Date Using localtime.

      So in this case, strftime would be more useful if you had a date/time and an interval to add/subtract. There are many other modules and benchmarks for benchmarking. brian_d_foy has a great section on Benchmarking in his Mastering Perl book.

      For higher level profiling, you should look at Devel::NYTProf.

Re: Operations with strftime
by parv (Parson) on Jun 17, 2014 at 11:19 UTC

    Try Time::HiRes to get the time difference via &tv_interval.

Re: Operations with strftime
by Anonymous Monk on Jun 17, 2014 at 11:08 UTC

    However, i get a warning:

    Yeah, strings aren't good for math operations :D Try storing time instead of stftime output

    Is there a better way to do this?

    Benchmark, it uses times