Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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; }

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":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found