Can someone enlighten me on the great disparity in speed?
Somewhat. Integer arithmetic is very close to being
the pathological case. There are machine instructions
expressly designed to do this stuff; very little
high-level structure is required (unless you want to
deal gracefully with adverse circumstances, such as
an overflow). As a result, low-level languages are
blazingly fast, because they cut out a lot of the
normal operational overhead, which turns out to be
the bulk of the runtime for a problem like this,
precisely because the problem itself is such a simple
one from the computer's perspective.
In case you hadn't noticed, you're looping several
hundred million times. The "slowness" you're seeing
in Perl is normal operational overhead,
and under more typical circumstances you'd never
notice it because it would get lost in the underflow.
Put something more substantial than integer arithmetic
inside that inner loop (in both C/C++ and Perl, the
same thing) and see what happens. For example, inside
the inner loop, write out a short message (maybe
including the number you're on) to a logfile.
Then compare.
{my$c;$ x=sub{++$c}}map{$ \.=$_->()}map{my$a=$_->[1];
sub{$a++ }}sort{_($a->[0 ])<=>_( $b->[0])}map{my@x=(&
$x( ),$ _) ;\ @x} split //, "rPcr t lhuJnhea eretk.as
o";print;sub _{ord(shift)*($=-++$^H)%(42-ord("\r"))};
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|