Skip to content

Instantly share code, notes, and snippets.

@xaicron
Created February 12, 2010 14:50
Show Gist options
  • Select an option

  • Save xaicron/302621 to your computer and use it in GitHub Desktop.

Select an option

Save xaicron/302621 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use Benchmark qw/timethese cmpthese/;
my @lines;
my $word = 'a';
push @lines, $word x $_ for 1..10000;
@lines = (@lines, @lines);
cmpthese timethese 0, {
one_liner => sub {
return [ sort { $b->[1] <=> $a->[1] } map { [$_, length $_] } do { my %h; grep { $h{$_}++ == 1 } @lines } ]->[0][0];
},
fast => sub {
my %h;
my $maxstr = '';
for (@lines) {
$maxstr = $_ gt $maxstr ? $_ : $maxstr if $h{$_}++ == 1;
}
return $maxstr;
},
fastest => sub {
my %h;
my $maxstr = '';
for (@lines) {
$maxstr = length $_ > length $maxstr ? $_ : $maxstr if $h{$_}++ == 1;
}
return $maxstr;
},
};
__END__
Benchmark: running fast, fastest, one_liner for at least 3 CPU seconds...
fast: 4 wallclock secs ( 3.00 usr + 0.17 sys = 3.17 CPU) @ 1.58/s (n=5)
fastest: 3 wallclock secs ( 3.09 usr + 0.08 sys = 3.17 CPU) @ 1.89/s (n=6)
one_liner: 4 wallclock secs ( 3.11 usr + 0.36 sys = 3.47 CPU) @ 1.44/s (n=5)
Rate one_liner fast fastest
one_liner 1.44/s -- -9% -24%
fast 1.58/s 9% -- -17%
fastest 1.89/s 31% 20% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment