You 'orig' variation never sets $t, but I don't think that matters much. Anyway, I made a slight variation, to reduce the chance the PRNG favours one method over the other:
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; } ], }; }
This shows 'sort' to be always slower, and 'grep' always winning:
Benchmarking 10 values Rate sort orig grep sort 34448/s -- -11% -53% orig 38503/s 12% -- -47% grep 72551/s 111% 88% -- Benchmarking 1000 values Rate sort orig grep sort 162/s -- -57% -62% orig 381/s 135% -- -11% grep 427/s 164% 12% -- Benchmarking 1000000 values (warning: too few iterations for a reliable count) (warning: too few iterations for a reliable count) (warning: too few iterations for a reliable count) s/iter sort orig grep sort 31.2 -- -83% -85% orig 5.18 502% -- -10% grep 4.67 567% 11% --

In reply to Re^6: Calculated % of data greater than $x in an array by JavaFan
in thread Calculated % of data greater than $x in an array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.