Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2013 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/68a59f2d8027273c70ab to your computer and use it in GitHub Desktop.
Save anonymous/68a59f2d8027273c70ab to your computer and use it in GitHub Desktop.
Benchmark sort
#!/usr/bin/perl
use Time::HiRes qw{time};
my @list = qw(B_5 A_11 C_0 A_10 A_1);
my $count = 100000;
my ( $then, $diff ) = ();
$then = time();
sort_with_splits(@list) for 1 .. $count;
$diff = time() - $then;
print "Sort with splits $diff seconds\n";
$then = time();
sort_with_maps(@list) for 1 .. $count;
$diff = time() - $then;
print "Sort with maps $diff seconds\n";
sub sort_with_splits {
return sort char_then_num @_;
}
sub sort_with_maps {
return map $_->[0],
sort { $a->[1] cmp $b->[1] || $a->[2] <=> $b->[2] }
map [ $_, split /_/ ], @_;
}
sub char_then_num {
my ( $a_char, $a_num ) = split '_', $a;
my ( $b_char, $b_num ) = split '_', $b;
return $a_char cmp $b_char
||
$a_num <=> $b_num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment