#!/usr/bin/perl # # $Id: for-loops 2592 2003-12-21 00:33:01Z jmates $ # # The author disclaims all copyrights and releases this document into # the public domain. # # for() loop speed comparisons. May want to add meat to the loops. use Benchmark qw(cmpthese); @data = (a .. z, A .. Z); # test the routines here #&tag; cmpthese( 100000, { 'c' => \&forc, 'perl' => \&forperl, 'perlish' => \&forperlish, 'while' => \&forwhile, 'perlvar' => \&forperlvar, } ); sub forc { for ($i = 0; $i < $#data; $i++) { ; } } sub forperl { for (@data) { ; } } sub forperlish { for (0 .. $#data) { ; } } sub forperlvar { for my $i (0 .. $#data) { ; } } # this is fast on threaded (5.005?) perls, slow otherwise sub forwhile { local $_ = 0; while ($_ < @data) { ; } continue { $_++ } } __END__ Results for perl 5.6.1 on FreeBSD 4.6 on a AMD Duron 800, 2002-08-21 Benchmark: timing 100000 iterations of c, perl, perlish, while... c: 5 wallclock secs ( 5.21 usr + 0.00 sys = 5.21 CPU) @ 19190.40/s (n=100000) perl: 3 wallclock secs ( 2.05 usr + 0.00 sys = 2.05 CPU) @ 48854.96/s (n=100000) perlish: 2 wallclock secs ( 2.05 usr + 0.00 sys = 2.05 CPU) @ 48854.96/s (n=100000) while: 6 wallclock secs ( 5.78 usr + 0.00 sys = 5.78 CPU) @ 17297.30/s (n=100000) Rate while c perlish perl while 17297/s -- -10% -65% -65% c 19190/s 11% -- -61% -61% perlish 48855/s 182% 155% -- 0% perl 48855/s 182% 155% 0% --