Edit: Apologies to ikegami for misreading his code. While the benchmark still more or less stands, my assertion that the output would differ was incorrect.
Your code will not produce the same output as the OP's. You indeed removed an O(N log N) loop, but at the cost of the sort. Even then, thanks to the grep and extra hash loop versus slice, the OP's (sorted) performance is 300% better than your unsorted code. Both unsorted, the gap widens to nearly 1000% with N = 1x105.
With N = 1x106, the gap shrinks a bit to 214% and 738%, respectively.
Perhaps I'm missing your point, though? Edit: Yup!
N = 1x105
Rate ikegami_sort ikegami op op_nosort
ikegami_sort 4.68/s -- -1% -75%% -91%
ikegami 4.72/s 1% -- -75%% -91%
op 19.1/s 308% 304% --% -62%
op_nosort 50.6/s 981% 970% 165% --
N = 1x106
Rate ikegami_sort ikegami op op_nosort
ikegami_sort 0.345/s -- -1% -68% -88%
ikegami 0.348/s 1% -- -68% -88%
op 1.08/s 214% 212% -- -63%
op_nosort 2.90/s 738% 733% 167% --
Test program:
use Benchmark qw/cmpthese timethese :hireswallclock/;
my $N = 1e6; # N
my @allrefs = map { 1e5 + int rand 9e5 } 1..$N;
my %uni_refs = map { 1e6 + int rand 9e6 => $_ } 1..$N;
cmpthese(timethese(-10, {
op => \&op,
op_nosort => \&op_nosort,
ikegami => \&ikegami,
ikegami_sort => \&ikegami,
}));
sub op {
my @refs = @allrefs[ sort { $a <=> $b } values %uni_refs ]
}
sub op_nosort {
my @refs = @allrefs[ values %uni_refs ]
}
sub ikegami {
my %keep = map { $_ => 1 } values %uni_refs;
my @refs = @allrefs[ grep $keep{$_}, 0..$#allrefs ];
}
sub ikegami_sort {
my %keep = map { $_ => 1 } values %uni_refs;
my @refs = @allrefs[ sort { $a <=> $b } grep $keep{$_}, 0..$#allre
+fs ];
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|