sub shuffle (@) {
my @a=\(@_);
my $n;
my $i=@_;
map {
$n = rand($i--);
(${$a[$n]}, $a[$n] = $a[$i])[0];
} @_;
}
####
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw/:all :hireswallclock/;
sub naive (@) {
my @l=@_;
for (reverse 1..$#l) {
my $r=int rand($_+1);
@l[$_,$r]=@l[$r,$_];
}
@l;
}
sub listutil (@) {
my @a=\(@_);
my $n;
my $i=@_;
map {
$n = rand($i--);
(${$a[$n]}, $a[$n] = $a[$i])[0];
} @_;
}
cmpthese -60, { map { $_ => "$_ 1..1000" } qw/naive listutil/ };
__END__
##
##
C:\temp>perl lus.pl
Rate naive listutil
naive 588/s -- -14%
listutil 684/s 16% --