5

I would like to take control of the output generated in seconds using perl. I would like to show the time (in seconds) in the form of days, hours, minutes and seconds to make it human readable format.

Code

my $start = time;
<some other perl codes>
my $duration = time - $start;
print "Total Execution time: $duration s\n";

Output is 311052 s

Required Output is 3 days 14 hours 24 minutes 12 seconds

Note: I am new to Perl. Before you flag this is as duplicate, I have done my research. I have gone through all the stackoverflow where similar solutions were discussed, none helped. My code is very small. What could be the few line changes that could be added.

arka.b
  • 204
  • 2
  • 13
  • 1
    Links to name a few: http://stackoverflow.com/questions/16019848/how-to-add-hours-minutes-seconds-in-perl, http://stackoverflow.com/questions/20049665/cant-control-how-hours-minutes-seconds-are-formatted-using-perls-datetimefo, http://stackoverflow.com/questions/7545664/is-there-a-cpan-module-for-converting-seconds-to-english, http://stackoverflow.com/questions/7545664/is-there-a-cpan-module-for-converting-seconds-to-english – arka.b Sep 14 '15 at 11:52
  • 3
    What's wrong with the last one you mention? – JB. Sep 14 '15 at 11:57
  • @JB - Adding just those modules will help? What changes should I add in those few lines of code? – arka.b Sep 14 '15 at 12:00
  • 3
    Going through half of the relevant StackOverflow answers won't help if you don't allow it to. – JB. Sep 14 '15 at 12:02

1 Answers1

14

You could use the Time::Piece and Time::Seconds modules, which will do all of this for you

In this program I have simply added pi days onto the current date and time to get a representative duration. You will, of course, use an actual time

use strict;
use warnings;

use Time::Piece;
use Time::Seconds qw/ ONE_DAY /;

my $start = localtime;
my $end = $start + int(355/113 * ONE_DAY);

my $duration = ($end - $start)->pretty;
print "Total Execution time: $duration\n";

output

Total Execution time: 3 days, 3 hours, 23 minutes, 53 seconds
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Your code worked perfectly. Small issue here, my execution time is random. Sometimes it generates **311052 s** sometimes only **17653 s** sometimes **24 s**. – arka.b Sep 14 '15 at 12:54
  • @arka.b: Why is that a problem? – Borodin Sep 14 '15 at 13:04
  • Yes, because my execution time varies. *Say* my execution ran for **12 hours 14 seconds** it will still show me **3 days, 3 hours, 23 minutes, 53 seconds** – arka.b Sep 14 '15 at 13:08
  • 1
    @arka.b: My second paragraph says *"In this program I have simply added pi days onto the current date and time to get a representative duration. You will, of course, use an actual time"*. You need to call `localtime` again to get the actual end time. I didn't imagine that all of your execution times were exactly 3.14 days! – Borodin Sep 14 '15 at 13:47