files/perl/benchmark/loop-two-elements.txt

Plain text | Download

  1. =head1 Looping two elements
  2.  
  3.  * Test case:  Which is the fastest way to loop two-and-two elements?
  4.  * Conclusion: hard to tell...
  5.  * Tester:     Jan Henning Thorsen
  6.  * Test app:   See below
  7.  
  8. Benchmark: timing 100 iterations of c_for, each...
  9.  
  10. =head2 Genuine Intel(R) CPU T2500  @ 2.00GHz
  11.  
  12.   c_for:  6 wallclock secs
  13.         ( 5.18 usr +  0.00 sys =  5.18 CPU) @ 19.31/s (n=100)
  14.    each:  4 wallclock secs
  15.         ( 4.40 usr +  0.03 sys =  4.43 CPU) @ 22.57/s (n=100)
  16.  
  17. =head2 AMD Athlon(tm) 64 X2 Dual Core Processor 4200+
  18.  
  19.   c_for:  5 wallclock secs
  20.         ( 5.46 usr +  0.00 sys =  5.46 CPU) @ 18.32/s (n=100)
  21.    each: 10 wallclock secs
  22.         (10.12 usr +  0.01 sys = 10.13 CPU) @  9.87/s (n=100)
  23.  
  24. =cut
  25.  
  26. #==============================================================================
  27.  
  28. use strict;
  29. use Benchmark;
  30.  
  31. my $values = [ 1..100_000 ];
  32.  
  33. timethese(100, {
  34.     'each' => sub {
  35.         for(my($key, $value) = each %{{ @$values }}) {
  36.             1;
  37.         }
  38.     },
  39.     'c_for' => sub {
  40.         for(my $i = 0; $i < @$values; $i+=2) {
  41.             my($key, $value) = @$values[$i, $i+1];
  42.             1;
  43.         }
  44.     },
  45. });