Random Walk:
Update: I bungled it. The results were suspiciously fast. When copying a block, I left in one of the --$i statements, so I was skipping every other element. Updated code & results:
'ROBO' => sub {
my $i = @array;
do {
++$cRO;
my $j = int rand $i;
@array[$i,$j] = @array[$j,$i];
} while ($i--);
},
roboticus@sparky:~$ perl 1088227.pl
Benchmark: timing 500 iterations of BRANCH, IFIDDLE, ROBO, WITHOUT...
BRANCH: 17 wallclock secs (17.05 usr + 0.00 sys = 17.05 CPU) @ 29
+.33/s (n=500)
IFIDDLE: 14 wallclock secs (14.29 usr + 0.00 sys = 14.29 CPU) @ 34
+.99/s (n=500)
ROBO: 19 wallclock secs (18.59 usr + 0.00 sys = 18.59 CPU) @ 26
+.90/s (n=500)
WITHOUT: 15 wallclock secs (15.69 usr + 0.00 sys = 15.69 CPU) @ 31
+.87/s (n=500)
5000000, 5250000, 5000000, 5125250
My code is still executing the wrong number of loops (the last number on the last line), but not so far out of line. Also, WITHOUT (second) also has an unexpected number of loops. Original node below:
You could also move the comparison to the end of the loop to avoid that +1:
'ROBO' => sub {
my $i = @array;
do {
my $j = int rand $i--;
@array[$i,$j] = @array[$j,$i];
} while (--$i);
},
Doing so gave me:
roboticus@sparky:~$ perl 1088227.pl
Benchmark: timing 500 iterations of BRANCH, IFIDDLE, ROBO, WITHOUT...
BRANCH: 17 wallclock secs (16.77 usr + 0.00 sys = 16.77 CPU) @ 29
+.82/s (n=500)
IFIDDLE: 14 wallclock secs (14.02 usr + 0.00 sys = 14.02 CPU) @ 35
+.66/s (n=500)
ROBO: 8 wallclock secs ( 7.85 usr + 0.00 sys = 7.85 CPU) @ 63
+.69/s (n=500)
WITHOUT: 15 wallclock secs (15.33 usr + 0.00 sys = 15.33 CPU) @ 32
+.62/s (n=500)
roboticus@sparky:~$
It seems to help (unless I bungled it).
...roboticus
When your only tool is a hammer, all problems look like your thumb.