in reply to Re^2: probabilistic pi algorithm
in thread probabilistic pi algorithm
Subroutine calls in Perl are expensive, especially when there's a few million of them, so inline as much as you can.
Benchmarking 3 variants reveals...
Rate original multiply powers original 0.405/s -- -72% -76% multiply 1.45/s 257% -- -14% powers 1.69/s 317% 17% --
use Benchmark 'cmpthese'; my $no_total = 1_000_000;#number of points my $d = 1000; sub gen_xy { ( int(rand($d)),int(rand($d)) ); } sub in_circle { my ($x,$y) = @_; ($x - $d/2)**2 + ($y - $d/2)**2 <= ($d/2)**2 ? 1 : 0; } my $subs = { powers => sub { my $no_in; $no_in += rand()**2 + rand()**2 <= 1 for 1 .. $no_total; return $no_in/$no_total * 4; }, multiply => sub { my $no_in; my ( $x, $y ); for ( 1 .. $no_total ) { ( $x, $y ) = ( rand, rand ); $no_in += $x*$x + $y*$y <= 1; } return $no_in/$no_total * 4; }, original => sub { my $d = 1000;#diameter my $no_in=0; $no_in += in_circle gen_xy for 1..$no_total; return $no_in/$no_total * 4; }, }; print "$_: ", $subs->{$_}->(), "\n" for keys %$subs; cmpthese( 5, $subs );
|
|---|