Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Fisher-Yates Shuffle

by roboticus (Chancellor)
on Jun 02, 2014 at 11:21 UTC ( [id://1088241]=note: print w/replies, xml ) Need Help??


in reply to Re: Fisher-Yates Shuffle
in thread Fisher-Yates Shuffle

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.

Replies are listed 'Best First'.
Re^3: Fisher-Yates Shuffle
by RichardK (Parson) on Jun 02, 2014 at 13:33 UTC

    That doesn't look right, now you're decrementing $i twice in each ROBO loop. Isn't that only doing half the work , hence taking half the time?

      RichardK:

      You're right. My code is all screwed up at the moment. I'll try to fix it correctly when I get off work today. <sigh...>

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1088241]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-18 05:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found