perlmeditation
LanX
Hi<P><P>
I never liked the usage of the CODEHASHREF in [mod://Benchmark].<P><P>
Often people start writing things like<P><P>
<c>
sub name1 {
...
}
sub name2 {
...
}
cmpthese (
-5,
{
'name1' => \&name1,
'name2' => \&name2,
}
)
</c><P><P>
which isn't very DRY and makes experimenting with optimizations really cumbersome! (I hate it, every new function name has to be repeated 3 times in different locations...)<P><P>
see also [id://1064279] for another examle.<P><P>
My idea is to put all subs into a dedicated package (defaultname "CMP" or so) and to automatically filter necessary name and coderefs.<P><P>
<c>
{
package CMP;
sub name1 {
...
}
sub name2 {
...
}
}
cmpthese (-5, pckg_subs("CMP") )
</c><P><P>
ATM I'm using a function pckg_subs() for this, not sure if it makes sense to extend the interface of <C>cmpthese</C> and <C>timethese</C> to directly accept a stash-ref like <c>\%CMP::</c>. ¹<P><P>
Following a proof on concept, request for comments.
<readmore>
<c>
use strict;
use warnings;
use Benchmark qw/cmpthese/;
use Data::Dump qw/pp/;
{
package CMP;
my @arr_1 = map {rand 1e6} 8000;
my @arr_2 = map {rand 1e6} 6000;
sub hash_values_diff {
my %diff3;
@diff3{@arr_1} = @arr_1;
delete @diff3{@arr_2};
values %diff3 ;
}
sub hash_key_diff {
my %diff3;
@diff3{@arr_1} = ();
delete @diff3{@arr_2};
keys %diff3 ;
}
sub using_vec {
my $vec = '';
vec( $vec, $_, 1 ) = 1 for @arr_2;
grep !vec( $vec, $_, 1 ), @arr_1;
}
sub hash_grep {
my %arr_2_hash;
undef @arr_2_hash{@arr_2};
grep !exists $arr_2_hash{$_}, @arr_1;
}
}
cmpthese(-5, pckg_subs() );
sub pckg_subs {
my $pckg_name= shift // "CMP";
my $stash = do {
no strict 'refs';
\ %{ "${pckg_name}::" };
};
# filter all subs from package
my $codehashref;
while (my ($name,$glob)= each %$stash) {
if ( my $cref = *{$glob}{CODE} ) {
print "$name:\t$glob\n";
$codehashref->{$name}=$cref;
}
}
return $codehashref;
}
</c>
OUTPUT
<c>
/usr/bin/perl -w /tmp/diff.pl
hash_grep: *CMP::hash_grep
hash_key_diff: *CMP::hash_key_diff
hash_values_diff: *CMP::hash_values_diff
using_vec: *CMP::using_vec
Rate using_vec hash_values_diff hash_key_diff hash_grep
using_vec 22269/s -- -85% -90% -91%
hash_values_diff 148869/s 568% -- -31% -40%
hash_key_diff 215078/s 866% 44% -- -13%
hash_grep 247455/s 1011% 66% 15% --
</c>
</readmore><P><P>
The idea code be extended with sub-attribute ':compare' or ':nocompare' to additionally mark functions which are supposed to be compared or not.<P><P>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-708738">
<p>Cheers Rolf
<p> <small>( addicted to the Perl Programming Language) </small>
</div></div>
<H5> update<P></H5><P>
¹) is it possible to tell if a hashref belongs to a stash? <P><P>
... well at least I could parse %main or pass the packagename directly =)