[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Moment of Zen



lr@hpl.hp.com wrote:
> 
> >     foreach $site (sort keys %sites) {
> >       #...
> >       my $mindshare = mindshare(...);
> >       $shares{$site} = $mindshare;
> >     }
> 
> Why an explicit (slow) loop?
> 
>       my %shares;
>       @shares{keys %sites} = map mindshare($_) => values %sites;

Why should foreach be any slower than map (which seems like a pretty
explicit loop to me)?  Even though the burden of proof lies with you, I
think you've done more than your fair share of benchmarks so I offer
this one.

#!/usr/local/bin/perl -w           

use strict;
use Benchmark;

my %sites;
my $w = shift;
my $s = 26 ** $w;
@sites{ ('a' x $w) .. ('z' x $w) } = 1 .. $s;
print "Testing $s elements\n";

timethese 1 << shift, {
    Map => sub {
        my %shares;
        @shares{keys %sites} = map mindshare($_) => values %sites;
    },
    For => sub {
        my %shares;
        $shares{$_} = mindshare($sites{$_}) for keys %sites;
    },
};

sub mindshare {
    return $_[0] + 1;
}

__END__
Testing 26 elements
Benchmark: timing 4096 iterations of For, Map...
       For:  3 wallclock secs ( 2.44 usr +  0.00 sys =  2.44 CPU)
       Map:  2 wallclock secs ( 2.52 usr +  0.00 sys =  2.52 CPU)

Testing 676 elements
Benchmark: timing 256 iterations of For, Map...
       For:  4 wallclock secs ( 3.98 usr +  0.00 sys =  3.98 CPU)
       Map:  5 wallclock secs ( 4.29 usr +  0.00 sys =  4.29 CPU)

Testing 17576 elements
Benchmark: timing 16 iterations of For, Map...
       For:  7 wallclock secs ( 7.10 usr +  0.01 sys =  7.11 CPU)
       Map:  8 wallclock secs ( 7.96 usr +  0.13 sys =  8.09 CPU)

-- 
Rick Delaney
rick.delaney@home.com

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe