Given a string of digits, I have to sum all digits as fast as possible using Perl.
My first implementation unpacks digits with unpack(), then sums the list of digits with List::Utils' sum(). It's pretty fast but is there a faster pack/unpack recipe for this task?
I tried with a pack/unpack combination, and benchmarked the two implementations. Used CPU time is almost the same; maybe is there some fast trick I'm not aware of?
Here is how I did my benchmark:
#!/usr/bin/env perl
use 5.012;
use strict;
use List::Util qw/sum/;
use Benchmark qw/timethese/;
timethese ( 1000000, {
list_util => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = sum( unpack( 'AAAAAAAAA', $CheckDigit ) );
} while ( $CheckDigit > 9 );
},
perl_only => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = unpack( '%16S*', pack( 'S9', unpack( 'AAAAAAAAA', $CheckDigit ) ) );
} while ( $CheckDigit > 9 );
},
} );