http://www.perlmonks.org?node_id=729073


in reply to Re: Why is this code so much slower than the same algorithm in C?
in thread Why is this code so much slower than the same algorithm in C?

Thanks for the comments. Here are a few more results, based on your suggestions and comments:

Yes, I acknowledged in the original post that the C algorithm is actually a bit less efficient. Putting the missing comparison into the Perl version instead of the loop label, as you have done, actually had no measurable effect on runtime.

Moving my ($i, j) outside the loop had no measurable effect on runtime. Also not too surprising.

Running your version exactly as listed took on average 48.8 +/- 0.1 sec—again no measurable change from my previous results.

True, I could use more rigorous methods to more accurately measure the effect of the above changes, but at best we'd be looking at a fraction of a percentage difference. Nowhere near the 3000+ % difference in the C version.

Adding use integer; to your version caused it to run in 46.8 sec, which is a marginal improvement. (My test machine has an FPU).

Not forgetting my original question of why this runs so slow, your optimization ideas do help shed a little light on a few of the factors that may be influencing performance.

It's perhaps important to underscore that my question is not, "what can I do to speed up this random little demonstration program", but instead, "why is Perl so much slower than C on some arbitrary, computationally expensive algorithm". Perhaps more to the point, "what are the factors influencing the performance of tight loops in Perl". (Or where could I read more about that topic!)

Hope that makes a bit more sense. Thanks again for your insights!

Replies are listed 'Best First'.
Re^3: Why is this code so much slower than the same algorithm in C? (ops)
by tye (Sage) on Dec 09, 2008 at 04:32 UTC

    Because the C code and the Perl code end up doing roughly equivalent things except that the C code runs through a few dozen machine-language instructions while the Perl code runs through a few dozen "opnodes". Machine-language instructions are the fastest unit of execution on a computer. While the slowness of opnode dispatch (each requires several dozen or even hundreds of machine-language instructions) is one of the motivations for some of the design changes in Perl 6.

    - tye