in reply to How Perl Optimize your code & some code TIPS ;-P

It seems to me that  if (condition) { statement } is sometime faster than  statement if condition With perl 5.6.0 I get:
use Benchmark ;timethese (200, { 'if_cond_then_statement'=> sub { ;my $ris=0 ;for my $i (0..100000) { if (int ($i/2)>7) { $ris+=1 } } } ,'statement_if_cond'=> sub { ;my $ris=0 ;for my $i (0..100000) { $ris+=1 if int ($i/7)>0 } } }) Benchmark: timing 200 iterations of if_cond_then_statement, statement_ +if_cond...if_cond_then_statement: 61 wallclock secs (58.33 usr + 0.0 +3 sys = 58.36 CPU) @ 3.43/s (n=200) statement_if_cond: 60 wallclock secs (59.15 usr + 0.01 sys = 59.16 CP +U) @ 3.38/s (n=200)
Am I missing something?

Replies are listed 'Best First'.
Re: Re: How Perl Optimize your code & some code TIPS ;-P
by pfaut (Priest) on Jan 25, 2003 at 17:27 UTC

    For one thing, you have different conditions. In the first you use if (int ($i/2)>7) and in the second you use if int ($i/7)>0. In this case, it won't make too much difference (the latter will execute the conditional code a couple more times) but if you want meaningful results from a benchmark, make sure all implementations under consideration do the same thing.

    On my system, if_cond_then_statement repeatedly beats out statement_if_cond with your original code and with it fixed using either of the if conditions above. The results are closer when both routines use the same if condition.

    Also, it is convention to put the semicolon (;) at the end of the line containing the instruction it terminates, not at the beginning of the next line. It makes for much more readable code.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';