homer
homer

Reputation: 433

Get Execution Time Difference and Display it in Seconds

I have browse SO for last 30 mins but couldn't get answer, so decided to post question.

I cannot use Time::Piece or Date::Parse module as suggested in some answers.

I'm trying to subtract two times and get result in seconds

use warnings;    
use strict;

$tod = `date "+%H:%M:%S"`; chomp $tod;  #record time of the day to variable
                                        #Sample time 16:55:44
my startTime = $tod;

 Insert records;

my endTime = $tod;

my totalTime = $startTime - $endTime;

Error: Arguemnt "16:55:14" isn't numeric in subtraction (-)

Thanks,

Upvotes: 1

Views: 1827

Answers (3)

barbasa
barbasa

Reputation: 675

If you cannot avoid to get the time as a string, you can use DateTime::Format::Strptime in combination with Datetime::Duration.

Bear in mind you will have to install it since it is not in the core modules...anyway here an example:

use warnings;    
use strict;
use DateTime::Format::Strptime;

my $strp = DateTime::Format::Strptime->new( pattern   => '%T', );

my $diff = $strp->parse_datetime("23:23:12") - $strp->parse_datetime("23:23:10");

print join('-',$diff->deltas()); #months-0-days-0-minutes-0-seconds-2-nanoseconds-0

Hope this helps!

Upvotes: 1

Schwern
Schwern

Reputation: 164729

Time::Piece has come with Perl since 5.10 which was seven years ago, I'm a bit dubious about your claim to not be able to use it and it's really going to cause a lot of unnecessary pain in the long term to not use modules. You can check these things using Module::CoreList. Anyhow...

You can convert the "HH:MM:SS" time of day into seconds since midnight. Fortunately you're using 24 hour time which makes this simpler.

sub time_of_day_to_seconds {
    my $tod = shift;

    my($hour, $min, $sec) = split /:/, $tod;

    my $total_seconds  = $sec;
    $total_seconds    += $min * 60;
    $total_seconds    += $hour * 60 * 60;

    return $total_seconds;
}

Upvotes: 4

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24063

You can use the time function:

my $start = time;
sleep 3;
my $end = time;

print $end - $start, ' seconds elapsed';

In general, it's best to avoid executing external commands with backticks or system when you can do the same thing with pure Perl.

If you want better than one-second resolution, you can use Time::HiRes as described in Is there a better way to determine elapsed time in Perl?

Upvotes: 7

Related Questions