use strict; use Benchmark; use vars '@array'; # The Fisher-Yates Shuffle # # my $arrayref = shift; # my $index = @$arrayref; # while ( $index-- ) # { # my $newloc = int rand (1+$i); # next if $index == $newloc; # @$arrayref[$index, $newloc] = @$arrayref[$newloc, $index]; # } @array = (1..100_000); # An array to be shuffled. # Rather then pass in a ref to the array, just shuffle the array in place. timethese( 100, { 'BRANCH' => sub { my $i=@array; while($i--){ my $j=int rand(1+$i); next if $i==$j; ### This is the line being tested. @array[$i, $j]=@array[$j, $i] }}, 'WITHOUT' => sub { my $i=@array; while($i--){ my $j=int rand(1+$i); @array[$i, $j]=@array[$j, $i] }}, } ); # Benchmark: timing 100 iterations of BRANCH, WITHOUT... # BRANCH: 73 wallclock secs (73.43 usr + 0.00 sys = 73.43 CPU) @ 1.36/s (n=100) # WITHOUT: 67 wallclock secs (67.02 usr + 0.00 sys = 67.02 CPU) @ 1.49/s (n=100) # Benchmark: timing 1000 iterations of BRANCH, WITHOUT... # BRANCH: 727 wallclock secs (726.67 usr + 0.00 sys = 726.67 CPU) @ 1.38/s (n=1000) # WITHOUT: 668 wallclock secs (667.78 usr + 0.02 sys = 667.80 CPU) @ 1.50/s (n=1000)