JupiterHost.Net ha scritto:
In benchmarking some code I've come across something I did not expect:

slice:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
my %n;@[EMAIL PROTECTED] = @k;
print "hi" if exists $n{1};
print "hi" if exists $n{3};
print "hi" if exists $n{5};
print "hi" if exists $n{7};
print "hi" if exists $n{9};
print "hi" if exists $n{11};

grep:
use strict;
use warnings;
my @k=qw(1 2 3 4 5 6);
print "hi" if grep /^1$/, @k;
print "hi" if grep /^3$/, @k;
print "hi" if grep /^5$/, @k;
print "hi" if grep /^7$/, @k;
print "hi" if grep /^9$/, @k;
print "hi" if grep /^11$/, @k;



Benchmark: timing 5000000 iterations of grep, slice...
grep: 3.65945 wallclock secs ( 2.33 usr + 0.04 sys = 2.37 CPU) @ 2109704.64/s (n=5000000)
slice: 2.37966 wallclock secs ( 2.52 usr + -0.01 sys = 2.51 CPU) @ 1992031.87/s (n=5000000)
Rate slice grep
slice 1992032/s -- -6%
grep 2109705/s 6% --


I would've thought the "slice and then use exists" would have been faster then "greping the entire array each time and using regexes" when you check it. but its consistently faster by an average 6-10%

Any ideas why that might be?


Just for curiosity, I ran a slightly different version of your benchmarks:

<code source="slice-bench.pl">
use strict;
use warnings;
use diagnostics;
my @k=qw(1 2 3 4 5 6);
my %n;
@[EMAIL PROTECTED] = @k;

my $times = 5000000;
my $dummy;

while($times--) {
    $dummy=1 if exists $n{1};
    $dummy=1 if exists $n{3};
    $dummy=1 if exists $n{5};
    $dummy=1 if exists $n{7};
    $dummy=1 if exists $n{9};
    $dummy=1 if exists $n{11};
}
</code>

<code source="grep-bench.pl">
use strict;
use warnings;
use diagnostics;
my @k=qw(1 2 3 4 5 6);

my $times = 5000000;
my $dummy;

while($times--) {
    $dummy=1 if grep /^1$/, @k;
    $dummy=1 if grep /^3$/, @k;
    $dummy=1 if grep /^5$/, @k;
    $dummy=1 if grep /^7$/, @k;
    $dummy=1 if grep /^9$/, @k;
    $dummy=1 if grep /^11$/, @k;
}
</code>

The results were:
<log shelltype="bash">
[EMAIL PROTECTED] time perl slice-bench.pl
9.15user 0.01system 0:09.89elapsed 92%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+1015minor)pagefaults 0swaps
[EMAIL PROTECTED] time perl grep-bench.pl
67.52user 0.01system 1:12.97elapsed 92%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+1015minor)pagefaults 0swaps
</log>

The slice version took about 10 seconds, the grep one took more than 1 minute.

Marcello

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to