1

I have an issue and this is rather my last resort before I give up, Im rather a noob with Perl and I've about reached the end of the internet searching for a solution.

***I do not have permission to install anything so it must be native to Perl5

I have a script and I need to calculate the total runtime of the script, and output the result in 00.00 "minutes.seconds" stored in a variable.

Here's a failed attempt:

#!/usr/bin/perl
use Time::Piece;
use POSIX qw(strftime);

my $start = localtime->strftime($unixtime);
sleep(10);
my $end = localtime->strftime($unixtime);
my $diff = $end - $start;
my $runtime = printf("%M.%S", $diff);
print $runtime;

I definitely have played with this a bit and was able to get "10" seconds as a result, however that is not the proper format. If the script ran for say 10 seconds, the output should be "00.10".

If the script ran for say 1 minute and 55 seconds the output should be "01.55".

Is there any way this can be done? I searched on this and found 1 article however not even close... REF: perl different time format output

Community
  • 1
  • 1
Autonomic
  • 150
  • 4
  • 15
  • 2
    Possible duplicate of [Convert seconds to days, hours, minutes using Perl](http://stackoverflow.com/questions/32564093/convert-seconds-to-days-hours-minutes-using-perl) – AbhiNickz Dec 06 '16 at 15:26

2 Answers2

2

No need for Time::Piece!

my $start = time;
sleep(10);
my $end = time;
my $diff = $end - $start;
my $runtime = sprintf '%d:%02d', int($diff / 60), $diff % 60;
print "$runtime\n";
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

This should do the trick:

#!/usr/bin/perl
use Time::Piece;

my $start = localtime;
sleep(10);
my $end = localtime;
my $diff = $end - $start;
my $minutes = int $diff->minutes;
my $seconds = $diff->seconds % 60;
my $output = sprintf '%02d.%02d', $minutes, $seconds;
print "$output\n";
ikegami
  • 367,544
  • 15
  • 269
  • 518
David Verdin
  • 480
  • 6
  • 18
  • Thank you very much David! I knew I was close but didnt know enough I guess about the %02d would bring it to the decimal point! – Autonomic Dec 06 '16 at 17:57
  • good. And I am really deeply sorry for my previous post. I really thought you needed metrics. This was not a cheap attempt at advertising a CPAN module. – David Verdin Dec 06 '16 at 18:13