White sand
White sand

Reputation: 41

Perl — Calculate timing difference in microseconds

I want to get time difference of below strings using Perl:

  1. 2013-12-27 13:28:14.975952
  2. 2013-12-27 13:28:16.345667 (microseconds).

I tried using mktime and getting millisec since the epoch but it’s not helping much.

If I use Time::HiRes module, how can I convert the above times to get the difference? Or do you have any better suggestions?

Upvotes: 0

Views: 1710

Answers (2)

chansen
chansen

Reputation: 2466

If DateTime and DateTime::Format::Strptime isn't an option, Time::Piece has been in core since 5.10.

use Time::Piece;

sub str2time {
    my ($str) = @_;
    $str =~ s/(\.[0-9]+)?\z//;
    my $fraction = $1 || 0;
    return Time::Piece->strptime($str, '%Y-%m-%d %H:%M:%S')->epoch + $fraction;
}

my $t1 = str2time('2013-12-27 13:28:14.975952');
my $t2 = str2time('2013-12-27 13:28:16.345667');

printf "difference: %f\n", $t2 - $t1;

Upvotes: 1

ikegami
ikegami

Reputation: 385655

use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y-%m-%d %H:%M:%S',
   on_error  => 'croak',
   time_zone => 'local',
);

sub parse_datetime {
   my ($str) = @_;

   my $nano;
   if ($str =~ /^([^.]*)\.(\d+)\z/) {
      $str = $1;
      $nano = "0.$2" * 1_000_000_000;
   } else {
      $nano = 0;
   }

   return $format->parse_datetime($str)->add( nanoseconds => $nano );
}

sub diff {
   return
      $_[1]->subtract_datetime_absolute($_[0])
         ->in_units('nanoseconds')
            / 1_000_000_000
}

my $dt1 = parse_datetime('2013-12-27 13:28:14.975952');
my $dt2 = parse_datetime('2013-12-27 13:28:16.0345667');
my $diff = diff($dt1, $dt2);
print("$diff\n");

But I'm a little confused. nothing in Time::HiRes returns something like 2013-12-27 13:28:14.975952. If you are actually using Time::HiRes::time, you can use the following:

use DateTime qw( );

sub diff {
   return
      $_[1]->subtract_datetime_absolute($_[0])
         ->in_units('nanoseconds')
            / 1_000_000_000
}

my $dt1 = DateTime->from_epoch( epoch => 1388461836.975952,  time_zone => 'local' );
my $dt2 = DateTime->from_epoch( epoch => 1388461838.0345667, time_zone => 'local' );
my $diff = diff($dt1, $dt2);
print("$diff\n");

Upvotes: 1

Related Questions