#! perl -slw use strict; use Data::Dump qw[ pp ]; use threads; use Time::HiRes qw[ time ]; sub thread { my $tid = threads->tid; my( $start, $end ) = @_; warn "$tid: processing $start to $end\n"; my $count = 0; for my $mon ( $start .. $end ) { $count += unpack '%32b*', pack 'N', $mon; } return $count; } our $T //= 1; our $M //= 1e6; my( $step, $s, @ranges ) = ( int $M / $T, 0 ); push( @ranges, [ $s, $s+$step -1] ), $s+=$step for 1 ..$T; $ranges[ -1][1] = $M; my $start = time; my @threads = map{ threads->create( \&thread, @$_ ); } @ranges; my $total = 0; $total += $_->join for @threads; printf "Total = %d (in %f seconds using $T threads)\n", $total, time()-$start; __END__ C:\test>888714 -M=100e6 -T=1 1: processing 0 to 100e6 Total = 1314447116 (in 46.340000 seconds using 1 threads) C:\test>888714 -M=100e6 -T=2 1: processing 0 to 49999999 2: processing 50000000 to 100e6 Total = 1314447116 (in 23.269000 seconds using 2 threads) C:\test>888714 -M=100e6 -T=3 1: processing 0 to 33333332 2: processing 33333333 to 66666665 3: processing 66666666 to 100e6 Total = 1314447116 (in 15.878000 seconds using 3 threads) C:\test>888714 -M=100e6 -T=4 1: processing 0 to 24999999 2: processing 25000000 to 49999999 3: processing 50000000 to 74999999 4: processing 75000000 to 100e6 Total = 1314447116 (in 12.960000 seconds using 4 threads)