Ok, so I tried Inline::C and it blows everything else away. Using the same 10 iterations, it doesn't run long enough for a decent benchmark. So changed to 100 iterations and it's under 2 seconds, where my best Perl implementation is taking 51 seconds.
Benchmark: timing 100 iterations of Inline::C, Algorithm::LUHN...
Inline::C: 2 wallclock secs ( 1.26 usr + 0.00 sys = 1.26 CPU) @ 79.37/s (n=100)
Algorithm::LUHN: 51 wallclock secs (51.57 usr + 0.00 sys = 51.57 CPU) @ 1.94/s (n=100)
#!/usr/bin/perl
use Benchmark;
use Inline C => DATA;
my %map = map { $_ => $_ } 0..9;
# cd1 is from https://metacpan.org/pod/Algorithm::LUHN
sub cd3 {
use integer;
my $total = 0;
my $flip = 1;
foreach my $c (reverse split //, shift) {
$c *= 2 unless $flip = !$flip;
while ($c) {
$total += $c % 10;
$c = $c / 10;
}
}
return (10 - $total % 10) % 10;
}
# example use:
my @range=(401135000000000..401135000099999);
timethese(100, {
'Algorithm::LUHN' => sub { for(@range){cd3($_)} },
'Inline::C' => sub { for(@range){cd4($_)} }
});
__END__
__C__
int cd4(char *number) {
int i, sum, ch, num, twoup, len;
len = strlen(number);
sum = 0;
twoup = 1;
for (i = len - 1; i >= 0; --i) {
ch = number[i];
num = (ch >= '0' && ch <= '9') ? ch - '0' : 0;
if (twoup) {
num += num;
if (num > 9) num = (num % 10) + 1;
}
sum += num;
twoup = ++twoup & 1;
}
sum = 10 - (sum % 10);
if (sum == 10) sum = 0;
return sum;
}