Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Curious Perl Behavior...

by linuxer (Deacon)
on May 25, 2010 at 21:41 UTC ( #841638=note: print w/ replies, xml ) Need Help??


in reply to Curious Perl Behavior...

You are measuring the time for creating the array reference. Don't do: print sum([1..100_000]); Do something like this:

#! /usr/bin/perl # vim:ts=4 sw=4 sts=4 et nu fdc=3: use strict; use warnings; use Benchmark qw( cmpthese ); #> sub routines #> ------------------------------------------------------------------- +--------- sub sum_list { my @numbers = @_; my $sum = 0; for my $num ( @numbers ) { $sum += $num; } return $sum; } sub sum_by_ref { my ( $numbers_ref ) = @_; my $sum = 0; for my $num ( @$numbers_ref ) { $sum += $num; } return $sum; } #> main script #> ------------------------------------------------------------------- +--------- my @numbers = 1 .. 1_000_000; cmpthese( -1, { 'sum_list' => sub { sum_list(@numbers); }, 'sum_by_ref' => sub { sum_by_ref(\@numbers); }, }); __END__
Result:
Rate sum_list sum_by_ref sum_list 4.42/s -- -45% sum_by_ref 8.00/s 81% --

I hope my point got clear ;o)

Addendum: Tested with creating list and reference directly within function call:

cmpthese( -1, { 'sum_list' => sub { sum_list(1..1_000_000); }, 'sum_by_ref' => sub { sum_by_ref([1..1_000_000]); }, }); Result: Rate sum_list sum_by_ref sum_list 4.13/s -- -9% sum_by_ref 4.55/s 10% --
edit: fixed missing "1.." in last snippet. Thanks ikegami. And fixed result output as well.


Comment on Re: Curious Perl Behavior...
Select or Download Code
Re^2: Curious Perl Behavior...
by ack (Deacon) on May 26, 2010 at 15:17 UTC

    Thanks, linuxer.

    I was trying to do it 'quick n dirty' and obviously did it *too* 'quick n dirty' without paying attention to what I was really doing.

    Your results make me feel more confident that I see what is going on and tought me (or re-tought me) a lesson that we talk about periodically in the Monestary: benchmarking is good...but do it right. The tools exist for a reason: to make it easy (or at least easier) to 'do it right'.

    I think I need to make a trip to the confessional.

    Again, thanks linuxer.

    ack Albuquerque, NM

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://841638]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2014-11-23 04:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (128 votes), past polls