Update: Another quantum leap brought to you by Inline::C and <time.h> for a 2500% increase over Date::Parse::str2time. Fast enough, I trust?
Updated with BrowserUk's method
This one's a natural for split (prior to getting really funky)
Benchmark code
#!/usr/bin/env perl
use 5.012;
use warnings;
use Benchmark qw/cmpthese/;
use Date::Parse; # str2time
use Time::Local qw/timegm_nocheck/;
my %mon;
@mon{qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/} = 0..11;
# For BrowserUk's sub
use constant MONTHS => { qw[
Jan 0 Feb 31 Mar 59 Apr 90 May 120 Jun 151
Jul 181 Aug 212 Sep 242 Oct 272 Nov 303 Dec 334
] };
use Inline C => q@
int epoch_sec(char * date) {
char *tz_str = date + 26;
struct tm tm;
int tz;
if ( strlen(date) != 31 ||
strptime(date, "%a, %d %b %Y %T", &tm) == NULL ||
sscanf(tz_str, "%d", &tz) != 1)
{
printf("Invalid date %s\n", date);
return 0;
}
return timegm(&tm) -
(tz < 0 ? -1 : 1)*(abs(tz)/100*3600 + abs(tz)%100*60);
}
@;
our $date = "Fri, 01 Mar 2013 01:21:14 +0200";
cmpthese(-3, {
str2time => sub { str2time($date) },
split_nocheck => sub {
my (undef, $dd, $Mm, $yyyy, $hh, $mm, $ss, $tz)
= split /[ ,:]+/o, $date;
timegm_nocheck($ss, $mm, $hh, $dd, $mon{$Mm}, $yyyy)
- ($tz < 0 ? -1 : 1)*(substr($tz,1,2)*3600 + substr($tz,3)
+*60)
},
BrowserUk => sub {
my( $d, $m, $y, $H, $M, $S, $tz ) = $date =~
m/^.... (\d\d) (...) (\d\d\d\d) (\d\d):(\d\d):(\d\d) ([+-]
+\d{4})/
or die "Bad format $date";
my $leaps = int( ($y - 1970) / 4 + 0.5 );
(((($y-1970)*365 +$leaps+MONTHS->{$m}+($d-1))*24 +$H)*60 +$M)*
+60 +$S
- ($tz < 0 ? -1 : 1)*(substr($tz,1,2)*3600 + substr($tz,3)
+*60)
},
inline_c => sub { epoch_sec($date) },
});
Output:
Rate str2time split_nocheck BrowserUk
+inline_c
str2time 16554/s -- -87% -93%
+ -96%
split_nocheck 126315/s 663% -- -45%
+ -71%
BrowserUk 229820/s 1288% 82% --
+ -47%
inline_c 437015/s 2540% 246% 90%
+ --
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|