Switching to an iterator-style for from the C-style for, using lexicals instead of globals reduces my running time from ten minutes thirty seconds to seven minutes thirty seconds. If you weren't aware the C-style for is equivalent to the pseudo-code initializer; while( condition ) { ... ; post_loop_action } which involves more steps than a .. iterator. In my example I moved the my() parts out of the tight loop because they have runtime implications. I used lexicals over globals because its one opcode lighter (a very, very cheap opcode though). Switching to 'use integer' further reduced the runtime to nine minutes forty five seconds (did I mention I'm doing this on an otherwise unburdoned machine?) and six minutes respectively.

The net effect is this particular form of "optimization" didn't buy me all that much but just shows that perl doesn't compete with simple things like that C++ which fits nicely within the processor's cache and is just a few instructions. The equivalent perl code is significantly more complex and of course takes longer. I wouldn't be surprised if most of the example's compiled C++ code was mostly register operations.

# The optimized perl code use strict; use warnings FATAL => 'all'; use integer; my $ans = 0; my $total; my $shift; for my $num ( 0 .. 16777216 ) { $total = 0; $shift = 1; for my $i ( 1 .. 24 ) { $total += $num & $shift ? $i : -$i; $shift <<= 1; } $ans++ if $total == 0; } print "$ans\n";

In reply to Re: Re: Believably slow.. by diotalevi
in thread Unbelievably slow.. by kiat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.