logie17 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I recently read this post on shuffling arrays. I put together a couple other methods of shuffling using the Knuth shuffle.
It looks like using the For loop is a bit faster. Thank you for any comments in advance.
Cheers!
I was wondering if I could get a little help to obfuscate the above benchmarks a little more? In true Perl style, such as perhaps using map or other better ways to iterate through the algorithm to help it gain even a better edge. Here are my benchmark results:#! /usr/local/bin/perl use strict; use warnings; my @randomarray = ( 0 .. 100 ); my $sub1 = sub { for(my $j, my $x, my $i = scalar @randomarray; $i;$j = int(ran +d($i)), $x = $randomarray[--$i], $randomarray[$i] = $randomarray[$j], + $randomarray[$j] = $x){ } }; my $sub2 = sub { my $i = scalar @randomarray; while ($i){ my $j = int(rand($i)); my $x = $randomarray[--$i]; #next value $randomarray[$i] = $randomarray[$j]; #next value = ran +dom value $randomarray[$j] = $x; #current random value = next va +lue. } }; use Benchmark; timethese(100000, { 'Sub 1' => $sub1, 'Sub 2' => $sub2, });
Benchmark: timing 100000 iterations of Sub 1, Sub 2... Sub 1: 28 wallclock secs (27.37 usr + 0.00 sys = 27.37 CPU) @ 36 +54.01/s (n=100000) Sub 2: 40 wallclock secs (32.25 usr + 0.00 sys = 32.25 CPU) @ 31 +00.78/s (n=100000)
It looks like using the For loop is a bit faster. Thank you for any comments in advance.
Cheers!
s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Array Shuffle
by GrandFather (Saint) on Jun 11, 2007 at 00:06 UTC | |
by ikegami (Patriarch) on Jun 11, 2007 at 14:43 UTC | |
by Limbic~Region (Chancellor) on Jun 11, 2007 at 16:43 UTC | |
by GrandFather (Saint) on Jun 11, 2007 at 19:11 UTC | |
by logie17 (Friar) on Jun 11, 2007 at 15:30 UTC |
Back to
Seekers of Perl Wisdom