Autonomic
Autonomic

Reputation: 170

Perl custom run time format

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

Upvotes: 1

Views: 260

Answers (2)

ikegami
ikegami

Reputation: 385655

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";

Upvotes: 2

David Verdin
David Verdin

Reputation: 490

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";

Upvotes: 1

Related Questions