Skip to content

Instantly share code, notes, and snippets.

@bowman
Created October 25, 2013 05:07
Show Gist options
  • Save bowman/7149652 to your computer and use it in GitHub Desktop.
Save bowman/7149652 to your computer and use it in GitHub Desktop.
Perl Benchmark script for Date validation methods. (Was cluttering $HOME)
#!/usr/bin/perl
#
# Benchmark script for Date validation methods.
#
use strict;
use warnings;
use Benchmark qw(:all :hireswallclock);
use DateTime;
use Time::Piece;
use Time::Local qw(timelocal);
use Date::Calc qw(check_date);
my $gooddate = '2009-02-01';
my $baddate = '2009-02-31';
our $dtre = qr/^(\d{4})-(\d\d)-(\d\d)$/;
our $format = '%Y-%m-%d'; # Also %F
# Check these all pass the good date:
die unless datetime($gooddate);
die unless tlocal($gooddate);
die unless timepiece($gooddate);
die unless datecalc($gooddate);
# Check they fail the invalid date:
die if datetime($baddate);
die if tlocal($baddate);
die if timepiece($baddate);
die if datecalc($baddate);
cmpthese(-5, { # ie. 5 seconds each
gooddatetime => sub { datetime($gooddate) },
goodtimepiece => sub { timepiece($gooddate) },
baddatetime => sub { datetime($baddate) },
badtimepiece => sub { timepiece($baddate) },
goodtimelocal => sub { tlocal($gooddate) },
badtimelocal => sub { tlocal($baddate) },
gooddatecalc => sub { datecalc($gooddate) },
baddatecalc => sub { datecalc($baddate) },
});
sub datetime {
my $date = shift;
eval {
$date =~ $dtre;
my $dt = DateTime->new(
year => $1,
month => $2,
day => $3
);
};
return(1) unless $@;
return;
}
sub timepiece {
my $date = shift;
my $match;
eval {
my $tp = Time::Piece->strptime($date, $format);
my $reverse = $tp->strftime($format);
$match = ($date eq $reverse);
};
return $match;
}
sub tlocal {
my $date = shift;
eval {
$date =~ $dtre;
my $time = timelocal(0,0,0, $3, ($2-1), $1);
};
return(1) unless $@;
return 0;
}
sub datecalc {
my $date = shift;
$date =~ $dtre;
my $check;
eval {
$check = check_date($1,$2,$3);
};
return $check;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment