MCE 1.831 and MCE::Shared 1.832 have been released containing the fix. What follows is the parallel demonstration for danaj's example. For sequence of numbers, the MCE bounds_only option is handy. Workers receive the begin and end values only.
use strict;
use warnings;
use ntheory 0.67 ":all";
use MCE::Flow 1.831;
my ( $name, $rng );
my %rand = (
"drand48" => sub { int(rand(1 << 32)) },
"ChaCha20" => sub { irand64() },
"/dev/urandom" => sub { unpack("Q", random_bytes(8)) }
);
# Workers receive [ begin, end ] values.
MCE::Flow::init(
max_workers => MCE::Util::get_ncpu(),
chunk_size => 10000,
bounds_only => 1,
user_begin => sub {
$name = MCE->user_args()->[0];
$rng = $rand{ $name };
}
);
sub func {
my ( $beg_seq, $end_seq ) = @{ $_ };
my ( $t ) = ( 0 );
for ( $beg_seq .. $end_seq ) {
$t++ if gcd( $rng->(), $rng->() ) == 1;
}
MCE->gather($t);
}
# The user_args option is how to pass arguments.
# Workers persist between each run.
sub cesaro {
my ( $name ) = @_;
print "Usage $name:\n";
for my $e ( 1..7 ) {
my $n = 10 ** $e;
my @ret = mce_flow_s { user_args => [$name] }, \&func, 0, $n - 1;
my $t = 0; $t += $_ for @ret;
printf "%8d %0.8f\n", $n, sqrt(6 * $n / $t);
}
printf "%9s %s\n\n", "Pi", Pi();
}
for ( "drand48", "ChaCha20", "/dev/urandom" ) {
cesaro($_);
}
Output.
Usage drand48:
10 3.46410162
100 3.11085508
1000 3.12347524
10000 3.15335577
100000 3.14122349
1000000 3.14092649
10000000 3.14209456
Pi 3.14159265358979
Usage ChaCha20:
10 3.46410162
100 3.08606700
1000 3.11588476
10000 3.14606477
100000 3.14461263
1000000 3.14453748
10000000 3.14269499
Pi 3.14159265358979
Usage /dev/urandom:
10 3.16227766
100 3.13625024
1000 3.24727816
10000 3.13959750
100000 3.14238646
1000000 3.14247180
10000000 3.14023908
Pi 3.14159265358979
The parallel code scales linearly. It runs about 4x faster on a machine with 4 "real" cores. A little faster with extra hyper-threads.
Regards, Mario
-
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.