For ou Foreach ?

#!/usr/bin/perl
 
use strict;
use warnings;
 
#attention $max = 10000000 => un process de 680Mo
my $max = 10000000;
my @tab = 0..$max;
my $time = {};
my $r = 0;
sub printtime {
  my ($loop) = @_;
  print "loop $max '$loop' time: ";
  print $time->{$loop}->{end} - $time->{$loop}->{start}, "s\n";
}
 
$time->{for}->{start} = time();
for (my $i = 0; $i <= $#tab; $i++) {
  $r += $tab[$i];
}
$time->{for}->{end} = time();
 
$r = 0;
$time->{for_sca}->{start} = time();
for (my $i = 0; $i < @tab; $i++) {
  $r += $tab[$i];
}
$time->{for_sca}->{end} = time();
 
$r = 0;
$time->{foreach}->{start} = time();
foreach my $elm (@tab) {
  $r += $elm;
}
$time->{foreach}->{end} = time();
 
$r = 0;
$time->{map}->{start} = time();
map {$r += $_} (@tab);
$time->{map}->{end} = time();
 
$r = 0;
$time->{while}->{start} = time();
while (@tab) {
  $r += shift @tab;
}
$time->{while}->{end} = time();
 
printtime('for');
printtime('for_sca');
printtime('foreach');
printtime('while');
printtime('map');

Voici les resultats obtenus :

bash-2.05b$ ./for-ou-foreach.pl
loop 10000000 'for' time: 11s
loop 10000000 'for_sca' time: 7s
loop 10000000 'foreach' time: 4s
loop 10000000 'while' time: 8s
loop 10000000 'map' time: 8s
bash-2.05b$ ./for-ou-foreach.pl
loop 10000000 'for' time: 11s
loop 10000000 'for_sca' time: 8s
loop 10000000 'foreach' time: 4s
loop 10000000 'while' time: 6s
loop 10000000 'map' time: 5s
bash-2.05b$ ./for-ou-foreach.pl
loop 10000000 'for' time: 12s
loop 10000000 'for_sca' time: 8s
loop 10000000 'foreach' time: 4s
loop 10000000 'while' time: 8s
loop 10000000 'map' time: 4s
bash-2.05b$ ./for-ou-foreach.pl
loop 10000000 'for' time: 12s
loop 10000000 'for_sca' time: 8s
loop 10000000 'foreach' time: 4s
loop 10000000 'while' time: 8s
loop 10000000 'map' time: 4s
bash-2.05b$ ./for-ou-foreach.pl
loop 10000000 'for' time: 13s
loop 10000000 'for_sca' time: 8s
loop 10000000 'foreach' time: 4s
loop 10000000 'while' time: 8s
loop 10000000 'map' time: 4s
 
tech/for_ou_foreach.txt · Dernière modification: 2006/08/26 11:45 par danjer
 
Recent changes RSS feed Valid XHTML 1.0 Valid CSS Driven by DokuWiki Powered by Lescampeurs