use strict; use warnings; use Benchmark qw( cmpthese ); for our $n ( map 10**$_, 1, 3, 6 ) { print "Benchmarking $n values\n"; my $l = int log $n; our @data = (); our @target = (); foreach (1 .. $l) { push @data, [map int rand $n, 1 .. $n]; push @target, int rand $n; } cmpthese -log $n, { orig => q[ for (my $i = 0; $i < @data; $i++) { my $c = 0; for my $elem (@{$data[$i]}) { $c++ if $elem > $target[$i]; } my $pct= (@{$data[$i]} - $c ) / @{$data[$i]} * 100; } ], sort => q[ for (my $i = 0; $i < @data; $i++) { my $c = 0; my @n = sort {$a <=> $b} @{$data[$i]}; $c++ while $n[$c] <= $target[$i]; my $pct= (@{$data[$i]} - $c ) / @{$data[$i]} * 100; } ], grep => q[ for (my $i = 0; $i < @data; $i++) { my $pct = grep({$_ > $target[$i]} @{$data[$i]}) / @{$data[$i]} * 100; } ], }; }