Well it occured to me that there would be some overhead... but how much? Is that overhead more then or less then the overhead of a branch? Well, honestly I don't know. But I ran a benchmark, and it came out close... Here is the code, followed by the results:
It looks to me like the branch is not needed.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 pl +ace. 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)
|
---|
Replies are listed 'Best First'. | |
---|---|
RE (tilly) 1: Fisher-Yates Shuffle
by tilly (Archbishop) on Aug 30, 2000 at 04:57 UTC | |
by Adam (Vicar) on Aug 30, 2000 at 05:25 UTC | |
by tilly (Archbishop) on Aug 30, 2000 at 06:51 UTC | |
by Adam (Vicar) on Aug 30, 2000 at 07:29 UTC | |
by BlaisePascal (Monk) on Aug 30, 2000 at 07:58 UTC | |
by tilly (Archbishop) on Aug 30, 2000 at 14:48 UTC | |
by tilly (Archbishop) on Aug 30, 2000 at 07:51 UTC | |
by tilly (Archbishop) on Aug 30, 2000 at 14:45 UTC | |
| |
Re: Fisher-Yates Shuffle
by Random_Walk (Prior) on Jun 02, 2014 at 06:20 UTC | |
by BrowserUk (Patriarch) on Jun 02, 2014 at 19:08 UTC | |
by Random_Walk (Prior) on Jun 04, 2014 at 14:38 UTC | |
by roboticus (Chancellor) on Jun 02, 2014 at 11:21 UTC | |
by RichardK (Parson) on Jun 02, 2014 at 13:33 UTC | |
by roboticus (Chancellor) on Jun 02, 2014 at 14:20 UTC | |
RE: Fisher-Yates Shuffle
by Anonymous Monk on Sep 08, 2000 at 01:57 UTC |