#! perl -slw
use strict;
use Time::HiRes qw[ time ];
use threads;
use Thread::Queue;
sub x {
my( $str, $v1, $v2 ) = @_;
my $result =0;
$result += (ord substr $str, $_, 1 ) * $v1 / $v2 for 0 .. length( $str ) -1;
return $result;
}
our $T //= 4;
our $N //= 100;
my $step = int( $N / $T );
my $now = time;
my $total :shared = 0;
my $str = 'the quick brown fox jumps over the lazy dog' x 100;
my( $start, $end ) = ( 0, $step );
my @threads = map{
my $thread = async{
for my $v1 ( $start .. $end ) {
for my $v2 ( 1 .. $N ) {
lock $total; ## Lock
$total += x( $str, $v1, $v2 ); ## update
}
}
};
$start += $step +1;
$end = $start + $step < $N ? $start + $step : $N;
$thread;
} 1 .. $T;
$_->join for @threads;
printf STDERR "With $T threads took %.6f seconds\n", time() - $now;
print $total;
__END__
c:\test>859242-2 -T=1 -N=100
With 1 threads took 14.250000 seconds
10711649268.1623
c:\test>859242-2 -T=2 -N=100
With 2 threads took 14.297000 seconds
10711649268.1623
c:\test>859242-2 -T=3 -N=100
With 3 threads took 14.476000 seconds
10711649268.1623
c:\test>859242-2 -T=4 -N=100
With 4 threads took 14.536000 seconds
10711649268.1623
####
#! perl -slw
use strict;
use Time::HiRes qw[ time ];
use threads;
use Thread::Queue;
sub x {
my( $str, $v1, $v2 ) = @_;
my $result =0;
$result += (ord substr $str, $_, 1 ) * $v1 / $v2 for 0 .. length( $str ) -1;
return $result;
}
our $T //= 4;
our $N //= 100;
my $step = int( $N / $T );
my $now = time;
my $total :shared = 0;
my $str = 'the quick brown fox jumps over the lazy dog' x 100;
my( $start, $end ) = ( 0, $step );
my @threads = map{
my $thread = async{
my $subtotal = 0;
for my $v1 ( $start .. $end ) {
for my $v2 ( 1 .. $N ) {
$subtotal += x( $str, $v1, $v2 ); ## no lock, local update
}
}
lock $total; ## lock
$total += $subtotal; ## update
};
$start += $step +1;
$end = $start + $step < $N ? $start + $step : $N;
$thread;
} 1 .. $T;
$_->join for @threads;
printf STDERR "With $T threads took %.6f seconds\n", time() - $now;
print $total;
__END__
c:\test>859242-2 -T=1 -N=100
With 1 threads took 14.115000 seconds
10711649268.1623
c:\test>859242-2 -T=2 -N=100
With 2 threads took 7.061000 seconds
10711649268.1623
c:\test>859242-2 -T=3 -N=100
With 3 threads took 4.827000 seconds
10711649268.1624
c:\test>859242-2 -T=4 -N=100
With 4 threads took 3.732000 seconds
10711649268.1623
c:\test>859242-2 -T=5 -N=100
With 5 threads took 4.356000 seconds
10711649268.1623
####
c:\test>859242-2 -T=1 -N=250
With 1 threads took 87.819000 seconds
78267011685.3423
c:\test>859242-2 -T=2 -N=250
With 2 threads took 43.342000 seconds
78267011685.3423
c:\test>859242-2 -T=3 -N=250
With 3 threads took 29.350000 seconds
78267011685.3423
c:\test>859242-2 -T=4 -N=250
With 4 threads took 23.113000 seconds
78267011685.3423