in reply to User Feedback for Subroutines with Long Execution Time
This is an ideal application for threading if that option is available to you.
#! perl -sw use strict; require 5.008; use threads 'yield'; use threads::shared; use vars qw[$ITERS]; $ITERS ||= 10000; $|=1; my $percent : shared = 0; sub progress{ print '[', ' ' x 80, ']', $percent; while( $percent < 1 ) { printf "\r[%s%s] %5.2f%% ", '#' x (80*$percent), ' 'x(80*(1-$p +ercent)), 100*$percent; yield; } print "\n"; return; } sub TakesALongTime{ my $in = 0; my $max = shift || 10000; for my $count ( 1 .. $max ) { $percent = $count/$max; rand () ** 2 + rand () ** 2 < 1 && $in ++ ; yield; } return sprintf '%f', 4 * $in / $max; } my $thread = threads->create('progress'); my $PI_approx = TakesALongTime($ITERS); $thread->join; print "After $ITERS iterations, pi was approximated to be: $PI_approx\ +n"; __END__ D:\Perl\test>261528 -ITERS=100000 [##################################################################### +##########] 100.00% After 100000 iterations, pi was approximated to be: 3.136440
Not a great demo, but if any of it needs explaination, please ask. (See Monte Carlo approximation of PI for Abigail's Monte Carlo approximation of PI snippet.)
|
|---|