Created
February 12, 2010 14:50
-
-
Save xaicron/302621 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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