Hi Monks,

I ran some C++ code and it took roughly 15 seconds to compute and print out the solution. I then converted the C++ code to perl and it took perl more than 15 mins to perform the same computation.

I'm wondering if there is something wrong with my perl code? Or is it the case the perl is inherently slow in this sort of computation? I've pasted both pieces of code here for your referral.
//begin c++ code #include<iostream> using namespace std; int main() { unsigned int ans=0; for(unsigned int num=0;num<16777216;++num) { int total=0; unsigned int shift=1; for(int i=1;i<=24;++i) { if(num & shift) { total+=i; } else { total-=i; } shift<<=1; } if(total==0) ++ans; } cout<<"Complete!"<<endl; cout<<"Answer is "<<ans<<endl; } //end c++ code #begin perl code $ans = 0; for($num=0;$num<16777216;$num++){ $total=0; $shift=1; for($i=1;$i<=24;$i++) { if($num & $shift) { $total+=$i; } else { $total-=$i; } $shift <<= 1; } $ans++ if $total == 0; } print "$ans\n"; # end perl code
Can someone enlighten me on the great disparity in speed?

In reply to 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.