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

Hi, I am using the Benchmark module as follows:-
use Benchmark; my $start_time = new Benchmark; my $end_time = new Benchmark; my $difference = timediff($end_time, $start_time); print ("It took ", timestr($difference), " to run everything.\n");
I would like to display the timediff results in hours (in addition to seconds, which the above does just fine). I am running into difficulties formatting the time units into something other than seconds.

There must be an easy way to do this, right?

Thanks,

-Fiddler42

Replies are listed 'Best First'.
Re: How to format Benchmark results in hours?
by FitTrend (Pilgrim) on Feb 10, 2005 at 16:36 UTC

    I have used the following code in the past to create hrs:mns:secs format

    This is from my older stuff and contains some excessive lines of code. Laziness has kept me away from optimizing it :). It doesn't conform to strict.

    $runTime = ConvertSeconds(TOTAL_SECONDS_HERE); print "$runTime\n"; sub ConvertSeconds($) { $hours = $minutes = $seconds = 0; ($minutes, undef) = split (/\./, "@_" / 60); $seconds = "@_" - ($minutes * 60); if ($minutes >= 60) { ($hours, undef) = split (/\./, $minutes / 60); $minutes = $minutes - ($hours * 60); } $minutes = "0$minutes" if (length($minutes) == 1); $seconds = "0$seconds" if (length($seconds) == 1); if ($hours) { $result = "$hours:$minutes:$seconds"; } else { $result = "$minutes:$seconds"; } return $result; }

    Hope this helps.

Re: How to format Benchmark results in hours?
by m-rau (Scribe) on Feb 10, 2005 at 16:49 UTC
    You can try something like this
    my $t = 12 * 60 * 60 # hours + 13 * 60 # minutes + 14; # seconds printf "%d hour(s), %d minute(s), %d second(s)\n", ( $t / 60 / 60 ), ( $t / 60 ) % 60, ( $t % 60 );
Re: How to format Benchmark results in hours?
by TedPride (Priest) on Feb 10, 2005 at 16:36 UTC
    my $difference = timediff($end_time, $start_time); my $sec = @$difference[0]; my $hour = sprintf('%0.2f', ($sec / 3600));
    This should work. EDIT: Changed so the hour formatting is better.
Re: How to format Benchmark results in hours?
by grinder (Bishop) on Feb 10, 2005 at 17:24 UTC
    There must be an easy way to do this, right?

    I wrote a snippet Formatting elapsed time to do just this. For instance, if your benchmark took 3661 seconds, it would return 1h1m1s. It will allow for durations of up to weeks. Now that I think about this code, the web app I wrote it for initially is still in use today.

    - another intruder with the mooring in the heart of the Perl

      I added some code to your snippet. This code formats the runtime depending on the length. It says, i.e.
      • 30 seconds
      • 5 minutes, 10 seconds
      • 1 hour, 15 minutes, 2 seconds
      • 2 days, 3 hours, 2 minutes, 59 seconds
      • etc.