Found a slightly different implementation here: https://github.com/bdlightner/luhn-implementation-Perl-

But, it's a little slower:

$ perl ./script
Benchmark: timing 10 iterations of Algorithm::LUHN, bdlightner...
Algorithm::LUHN:  7 wallclock secs ( 6.89 usr +  0.00 sys =  6.89 CPU) @  1.45/s (n=10)
bdlightner:  8 wallclock secs ( 7.69 usr +  0.00 sys =  7.69 CPU) @  1.30/s (n=10)
The benchmark code and both implementations:
#!/usr/bin/perl use Benchmark; my %map = map { $_ => $_ } 0..9; # cd1 is from https://metacpan.org/pod/Algorithm::LUHN sub cd1 { my @buf = reverse split //, shift; my $totalVal = 0; my $flip = 1; foreach my $c (@buf) { my $posVal = $map{$c}; $posVal *= 2 unless $flip = !$flip; while ($posVal) { $totalVal += $posVal % 10; $posVal = int($posVal / 10); } } return (10 - $totalVal % 10) % 10; } # cd2 is from: https://github.com/bdlightner/luhn-implementation-Perl- sub cd2 { my($number) = @_; my($i, $sum, $ch, $num, $twoup, $len); $len = length($number); $sum = 0; $twoup = 1; for ($i = $len - 1; $i >= 0; --$i) { $ch = substr($number, $i, 1); $num = unpack('c', $ch) - 0x30; $num += $num if ($twoup); $num = int($num / 10) + ($num % 10) if ($num > 9); $sum += $num; $twoup = (++$twoup) & 1; } $sum = 10 - ($sum % 10); $sum = 0 if ($sum == 10); return $sum; } # example use: my @range=(401135000000000..401135000099999); timethese(10, { 'Algorithm::LUHN' => sub { for(@range){cd1($_)} }, 'bdlightner' => sub { for(@range){cd2($_)} }, });

In reply to Re: Faster Luhn Check Digit Calculation? by kschwab
in thread Faster Luhn Check Digit Calculation? by kschwab

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.