Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Faster Luhn Check Digit Calculation?

by kschwab (Vicar)
on Nov 30, 2018 at 19:14 UTC ( [id://1226550]=note: print w/replies, xml ) Need Help??


in reply to Faster Luhn Check Digit Calculation?

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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1226550]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-25 13:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found