What is the fastest date to timestamp conversion method in Perl. I mean as fast as date command. This is very strange as converting date to timestamp in Perl is real pain. I used Date::Parse, Time::Piece, Date::Time modules. All makes the code to run slower.

Let me give you example, once I run the code with out date conversion it is finishing in 9 sec. Once I add the class call and make conversion it is causing me 48 sec more. Only difference between 2 versions is given bellow. Of couse used module here is Date::Parse

my $tmst = str2time($each[0]." ".$each[1]);

Two variables are coming from a file and one of them is Date and other is time. Does anybody know the faster way to make this conversion,

Appriciate your responses
Thanks

有帮助吗?

解决方案

str2time is slow because it supports so many different date and time formats, and has to try to guess which format the incoming date and time is in before parsing it.

If you don't need that, and your date format is very simple, then using something like mktime from the POSIX module (which is part of the Perl core) will be significantly faster. This benchmark shows about a 640% speed up:

#!/usr/bin/env perl
use strict;
use warnings;
use POSIX qw(mktime);
use Date::Parse qw(str2time);
use Benchmark qw(cmpthese);

sub to_stamp {
  $_[0] =~ /\A(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\z/
    and mktime($6, $5, $4, $3, $2-1, $1-1900);
}

print to_stamp('2014-04-27 12:17:30'), "\n";
print str2time('2014-04-27 12:17:30'), "\n";

cmpthese -1, {
  to_stamp => q[  to_stamp('2014-04-27 12:17:30')  ],
  str2time => q[  str2time('2014-04-27 12:17:30')  ],
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top