Created
January 25, 2014 23:45
-
-
Save iarna/8625596 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
use strict; | |
use warnings; | |
use Benchmark; | |
use List::MoreUtils qw(minmax uniq part); | |
use Test::More tests => 1; | |
my @set; push @set, int(rand()*1000) for 1..10_000; | |
my $pivot_a = 333; | |
my $pivot_b = 666; | |
my %benchmarks = ( | |
'ListMoreUtils' => sub { | |
my ($set_min, $set_max) = minmax @set; | |
my @unique_set = uniq @set; | |
my (undef,$sub_set_a) = part { $_ <= $pivot_a } @set; | |
my (undef,$sub_set_b) = part { $_ > $pivot_a and $_<=$pivot_b } @set; | |
my (undef,$sub_set_c) = part { $_ > $pivot_b } @set; | |
return [$set_max, $set_min, \@unique_set, $sub_set_a, $sub_set_b, $sub_set_c]; | |
}, | |
'ForLoop' => sub { | |
my ($set_min,$set_max,%unique,@sub_set_a,@sub_set_b,@sub_set_c); | |
foreach my $item (@set){ | |
$set_max = $item if (! defined $set_max || $item > $set_max); | |
$set_min = $item if (! defined $set_min || $item < $set_min); | |
$unique{$item}=1; | |
push(@sub_set_a,$item) if ($item <= $pivot_a); | |
push(@sub_set_b,$item) if (($item > $pivot_a) and ($item <= $pivot_b)); | |
push(@sub_set_c,$item) if ($item > $pivot_b); | |
} | |
return [$set_max, $set_min, [keys %unique], \@sub_set_a, \@sub_set_b, \@sub_set_c]; | |
}, | |
); | |
timethese(1_000, \%benchmarks); | |
use Data::Dumper qw( Dumper ); | |
my $result_a = $benchmarks{'ListMoreUtils'}->(); | |
my $result_b = $benchmarks{'ForLoop'}->(); | |
for ($result_a,$result_b) { | |
for my $ii (2,3,4,5) { | |
$_->[$ii] = [sort {$a<=>$b} @{$_->[$ii]}]; | |
} | |
} | |
is_deeply( $result_a, $result_b, "Do they match"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment