loop-two-elements.txt

=head1 Looping two elements

 * Test case:  Which is the fastest way to loop two-and-two elements?
 * Conclusion: hard to tell...
 * Tester:     Jan Henning Thorsen
 * Test app:   See below

Benchmark: timing 100 iterations of c_for, each...

=head2 Genuine Intel(R) CPU T2500  @ 2.00GHz

  c_for:  6 wallclock secs
        ( 5.18 usr +  0.00 sys =  5.18 CPU) @ 19.31/s (n=100)
   each:  4 wallclock secs
        ( 4.40 usr +  0.03 sys =  4.43 CPU) @ 22.57/s (n=100)

=head2 AMD Athlon(tm) 64 X2 Dual Core Processor 4200+

  c_for:  5 wallclock secs
        ( 5.46 usr +  0.00 sys =  5.46 CPU) @ 18.32/s (n=100)
   each: 10 wallclock secs
        (10.12 usr +  0.01 sys = 10.13 CPU) @  9.87/s (n=100)

=cut

#==============================================================================

use strict;
use Benchmark;

my $values = [ 1..100_000 ];

timethese(100, {
    'each' => sub {
        for(my($key, $value) = each %{{ @$values }}) {
            1;
        }
    },
    'c_for' => sub {
        for(my $i = 0; $i < @$values; $i+=2) {
            my($key, $value) = @$values[$i, $i+1];
            1;
        }
    },
});