use strict; use warnings; use Imager; 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 => $x, y => $y, color => $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 = Imager->new( xsize => $width, ysize => $height ); push @palette, Imager::Color->new( 0, 0, 0 ); # black for ( 1 .. $iterations ) { my ( $r, $g, $b ) = map { int rand 255 } 1 .. 3; push @palette, Imager::Color->new( $r, $g, $b ); } # compute mandelbrot $mce->process({ bounds_only => 1, sequence => [ 0, $width - 1 ] }); $mce->shutdown; # save image my $file = qq(mandelbrot.png); $image->write( file => $file );