Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Does Perl do something funny if you mess with the upper limit on a for-loop? It would seem that the code "wit" below would run faster (by 2) since it does half the loops, but it runs longer! Here's my code and output:
use Benchmark Benchmark::cmpthese( -10, { non => sub{my $g = 10; my $lim = 10; for ( my $i = 1; $i < $lim; ++$i ) { --$g }}, wit => sub{my $g = 10; my $lim = 10; for ( my $i = 1; $i < $lim; ++$i ) { --$lim }} } ) __END__ Rate non wit non 507747/s -- -26% wit 685879/s 35% --

Replies are listed 'Best First'.
Re: for limit
by Limbic~Region (Chancellor) on Nov 04, 2008 at 15:49 UTC
    Anonymous Monk,
    but it runs longer!

    I am not sure how you are interpreting these results, but the wit is running faster. As to why it isn't the 50% expected, I would suggest you run the following instead:

    #!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; cmpthese( -25, { non => sub{my $g = 100_000; my $lim = 100_000; for ( my $i = 1; $i < $lim; ++$i ) { --$g }}, wit => sub{my $g = 100_000; my $lim = 100_000; for ( my $i = 1; $i < $lim; ++$i ) { --$lim }} } ); __DATA__ Rate non wit non 103/s -- -50% wit 206/s 99% --

    Cheers - L~R

Re: for limit
by BrowserUk (Patriarch) on Nov 04, 2008 at 15:58 UTC

    Firstly, you are misinterpreting the output. In your example, wit (where the limit is being changed), runs 35% faster than non as it should.

    And as you increase the number of iterations of the for loop, thereby reducing the significance of the benchmarking overhead, so the difference gets closer and closer to the 2x faster you are expecting:

    c:\test>junk Rate non wit non 381539/s -- -32% wit 559590/s 47% -- c:\test>junk -N=100 Rate non wit non 46194/s -- -47% wit 87401/s 89% -- c:\test>junk -N=1000 Rate non wit non 4763/s -- -50% wit 9557/s 101% -- c:\test>junk -N=1e5 Rate non wit non 48.8/s -- -50% wit 96.8/s 98% -- c:\test>junk -N=1e6 Rate non wit non 4.80/s -- -50% wit 9.55/s 99% --

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: for limit
by moritz (Cardinal) on Nov 04, 2008 at 15:50 UTC
    It would seem that the code "wit" below would run faster (by 2) since it does half the loops, but it runs longer!
    No, the wit part of the benchmark runs 0.68 million times per second, while the non part runs 0.51 million times per second.

    So it does run faster (by a factor of 35%).

Re: for limit
by Anonymous Monk on Nov 04, 2008 at 16:05 UTC
    thank you, I see now my error.