syntax error at /tmp/615254.pl line 41, near "N
push"
After some correction (and addition to print out the sorted array), here is the result:
0 1 3 2 4 5 7 8 6
1 0 3 8 2 4 7 6 5
2 3 8 0 1 4 7 5 6
3 0 1 2 8 7 6 4 5
4 8 7 0 1 2 6 3 5
5 0 7 1 2 3 6 8 4
6 7 8 3 4 1 2 0 5
7 6 8 3 4 0 1 5 2
8 7 6 3 4 1 2 0 5
This orcish manuever is really new to me. And I'm tempted to benchmark these two techniques. Here it goes:
#!/usr/bin/perl
use strict;
use warnings;
my @sim_st = qw(
1.0 0.9 0.3 0.6 0.3 0.3 0.2 0.3 0.3
0.9 1.0 0.3 0.5 0.3 0.1 0.2 0.3 0.4
0.3 0.3 1.0 0.6 0.3 0.2 0.2 0.3 0.4
0.6 0.6 0.6 1.0 0.2 0.2 0.3 0.4 0.5
0.3 0.3 0.3 0.2 1.0 0.1 0.3 0.4 0.5
0.3 0.2 0.2 0.2 0.1 1.0 0.2 0.3 0.2
0.1 0.2 0.2 0.3 0.3 0.1 1.0 0.8 0.6
0.3 0.3 0.2 0.4 0.4 0.3 0.8 1.0 0.8
0.3 0.4 0.4 0.5 0.5 0.2 0.6 0.8 1.0
);
my @sim_om = @sim_st;
use Benchmark 'cmpthese';
my $count = shift || -1;
cmpthese $count, {
sort_with_st => \&sort_st,
sort_with_om => \&sort_om,
};
sub sort_st {
my @sim = @sim_st;
my @sorted =
map { $_->[0] }
map {
my $i = 0;
sort { $b->[1] <=> $a->[1] }
map { [$i++, $_] } splice (@sim, 0, 9)
}
0..8;
}
use constant { M => 9, N => 9 };
sub sort_om {
my @index_sorted;
for my $m (0..(M-1)) {
my $ix0 = $m * N;
push @index_sorted,
sort { $sim_om[$ix0 + $b] <=> $sim_om[$ix0 + $a] }
0..(N-1);
}
}
And here is the benchmark, kinda speaks for itself:
$ perl benchmark-sort.pl
Rate sort_with_st sort_with_om
sort_with_st 3011/s -- -61%
sort_with_om 7724/s 156% --
Thanks and ++ goes to shmem and salva for the lessons.
Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!
|