星期四, 8月 24, 2017

Perl — Calculate timing difference in microseconds

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;


This can be used to analyze the trace for performance issue.

Note:

||                              if the left operand is true, the right operand is not even evaluated.
\z                             Match only at end of string
 ?                             Match 1 or 0 times
$var =~ s/A/B/       
把變數 $var 內的第一個A子字串整個代換成B子字串。特別注意第一部份(A)為RE, 但第二部分(B)僅為字串

http://irw.ncut.edu.tw/peterju/perl.html

$str =~ s/(\.[0-9]+)?\z//   => 表示將小數點後(含小數點)的部分用空字串取代, 也就是移除
$fraction = $1 || 0            => 表示若有找到小數點後的部分, 即把其值copy 給fraction, 不然就設為0




沒有留言: