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;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|