The GD module is nearly 2x faster than Imager. Not sure why. Anyway, here is the parallel version using GD. Workers are spawned prior to the image being created by the manager process.
use strict; use warnings; use GD; use MCE; # based on original http://www.alfrog.com/mandel.html # karlgoethebier: code refactor # marioroy: parallelization my $width = 1280; my $height = 1024; my $iterations = 20; my @palette; my $image; my $mce = MCE->new( use_threads => 0, # MCE defaults to threads on Windows max_workers => 'auto', chunk_size => 8, gather => sub { my ( $x, $y, $color ); while ( ($x, $y, $color) = splice(@_, 0, 3) ) { $image->setPixel( $x, $y, $palette[ $color ] ); } }, user_func => sub { my ( $mce, $chunk_ref, $chunk_id ) = @_; my ( $re_c, $im_c, $re_z, $im_z, $color, $temp ); my ( @set_data ); for my $x ( $chunk_ref->[0] .. $chunk_ref->[1] ) { for my $y ( 0 .. $height - 1 ) { $re_c = ( $x - 3 * $width / 4 ) / ( $width / 3 ); $im_c = ( $y - $height / 2 ) / ( $width / 3 ); $re_z = $im_z = $color = 0; while ( 1 ) { $temp = $re_z; $re_z = $re_z * $re_z - $im_z * $im_z + $re_c; $im_z = 2 * $temp * $im_z + $im_c; ++$color; last if $re_z * $re_z + $im_z * $im_z > 4; if ( $color == $iterations ) { $color = 0; last; } } push @set_data, $x, $y, $color; } } MCE->gather( @set_data ); } ); # spawn MCE workers $mce->spawn; # init image and color palette $image = new GD::Image( $width, $height ); push @palette, $image->colorAllocate( 0, 0, 0 ); # black for ( 1 .. $iterations ) { my ( $r, $g, $b ) = map { int rand 255 } 1 .. 3; push @palette, $image->colorAllocate( $r, $g, $b ); } # compute mandelbrot $mce->process({ bounds_only => 1, sequence => [ 0, $width - 1 ] }); $mce->shutdown; # save image open my $fh, '>mandelbrot.png' || exit 1; binmode $fh; print $fh $image->png; close $fh;
In reply to Re^2: Refactoring: Better Variable Names For Better Understanding? [SOLVED]
by marioroy
in thread Refactoring: Better Variable Names For Better Understanding? [SOLVED]
by karlgoethebier
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |