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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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.

In reply to Re: Curious Perl Behavior... by linuxer
in thread Curious Perl Behavior... by ack

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-25 14:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found