oldgeezer wrote:
> Hi all,
> 
> Last week I discovered this perl.beginners group.
> Good stuff here, albeit many times hard to grasp
> the answers. But I'm learning.
> 
> What I would like to understand is why looping
> 2 times through 5000 lines takes less time than
> looping 5000 times through 2 lines.
> 
> To show what I mean, I wrote a snippet that
> does nothing with the data and yet the first
> part is 5 times faster than the second part
> (in my pc anyway).
> 
> Thanks.
> Rob.
> 
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use POSIX qw(clock);
> 
> #just create a small array for this test
> my @few=();
> for my $i(1...2){push @few, $i};
> 
> #just create a big array for this test
> my @many=();
> for my $i(1...500000){push @many, $i};
> 
> # part 1, loop few times over much data
> my $time_1=clock();
> foreach my $val (@few){
>     foreach my $other(@many) {} #do zilch
> }
> my $time_2=clock();
> my $delta1=$time_2-$time_1;
> print "Delta1 $delta1\n";
> 
> # part 2, loop many times over few data
> my $time_3=clock();
> foreach my $val (@many){
>     foreach my $other(@few) {} #do zilch
> }
> my $time_4=clock();
> my $delta2=$time_4-$time_3;
> print "Delta2 $delta2\n";
> 
> exit 0;

In addition to what others have said, it is worth doing the same experiment for
an empty loop:

  foreach my $val (@many){
  }

to see how much overhead there is for each iteration of the loop.

You should also investigate the Benchmark module, which makes comparisons such
as these more convenient.

Rob

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


Reply via email to