Hello again,
you guessed rigth! use integer; boosts performance (if I have build my benchmarks correctly..)
use strict;
use warnings;
use Benchmark qw(cmpthese timethese);
######################################################################
+##########
my $results = timethese($ARGV[0]//-5, {
'no_integer_module ' =>\&no_integer,
'with_integer_module' =>\&with_integer,
});
cmpthese( $results );
######################################################################
+##########
sub no_integer{
my $n=1002;
my $len = 1 + 10 * $n / 3;
my $pi;
my @a= (2) x $len;
my $nines = 0;
my $predigit = 0;
for (my $j =1; $j < $n + 1; ++$j){
my $q = 0;
for my $i (reverse 0..$len - 1) {
my $x = 10 * $a[$i] + $q * ($i + 1);
my $divisor = 2 * $i + 1;
$a[$i] = $x % $divisor;
$q = $x / $divisor;
}
$a[0]=$q%10;
$q=$q/10;
if (9 == $q){ ++$nines; }
elsif(10 == $q){
$pi.=$predigit + 1;
for (my $k = 0; $k < $nines; $k++){$pi.=0} # print 0
$predigit = $nines = 0;
}
else{
$pi.= $predigit;
$predigit = $q;
if(0 != $nines){
for (my $k = 0; $k < $nines; $k++) {
$pi.=9;
}
$nines = 0;
}
}
}
}
######################################################################
+##########
sub with_integer{
use integer;
my $n=1002;
my $len = 1 + 10 * $n / 3;
my $pi;
my @a= (2) x $len;
my $nines = 0;
my $predigit = 0;
for (my $j =1; $j < $n + 1; ++$j){
my $q = 0;
for my $i (reverse 0..$len - 1) {
my $x = 10 * $a[$i] + $q * ($i + 1);
my $divisor = 2 * $i + 1;
$a[$i] = $x % $divisor;
$q = $x / $divisor;
}
$a[0]=$q%10;
$q=$q/10;
if (9 == $q){ ++$nines; }
elsif(10 == $q){
$pi.=$predigit + 1;
for (my $k = 0; $k < $nines; $k++){$pi.=0} # print 0
$predigit = $nines = 0;
}
else{
$pi.= $predigit;
$predigit = $q;
if(0 != $nines){
for (my $k = 0; $k < $nines; $k++) {
$pi.=9;
}
$nines = 0;
}
}
}
}
Benchmark: running no_integer_module , with_integer_module for at lea
+st 20 CPU seconds...
no_integer_module : 21 wallclock secs (20.64 usr + 0.00 sys = 20.64
+CPU) @ 0.92/s (n=19)
with_integer_module: 21 wallclock secs (20.50 usr + 0.00 sys = 20.50
+CPU) @ 1.37/s (n=28)
s/iter no_integer_module with_integer_module
no_integer_module 1.09 -- -33%
with_integer_module 0.732 48% --
I read in the docs of the integer module:
> On many machines, this doesn't matter a great deal for most computations, but on those without floating point hardware, it can make a big difference in performance.
The above results show that my machine has not floating point hardware?
Thanks also for the link to the spigot explication; I must admit that yesterday night I've understood almost nothing.. I'll try under sun beans.
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.