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


In reply to Re^3: probabilistic pi algorithm by FunkyMonk
in thread probabilistic pi algorithm by spx2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.