Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Cameron Laird
claird at lairds.us
Sun Sep 2 11:39:34 EDT 2007
In article <1188742231.470668.29910 at g4g2000hsf.googlegroups.com>,
Mark Dickinson <dickinsm at gmail.com> wrote:
>On Sep 2, 9:45 am, jwrweather... at gmail.com wrote:
>> [snip code]
>>
>> Thanks for that. I realise that improving the algorithm will speed
>> things up. I wanted to know why my less than perfect algorithm was so
>> much slower in python than exactly the same algorithm in C. Even when
>> turning off gcc's optimiser with the -O0 flag, the C version is still
>>
>> > 100 times quicker.
>
>Well, for one thing, you're creating half a million xrange objects in
>the course of the search. All the C code has
>to do is increment a few integers.
>
>Mark
>
Right: Mr. Dickinson's original question is entirely
legitimate, and it's not adequate to respond, as some
follow-ups did, with ways to improve the Python-coded
algorithm.
The correct answer, which I want to reinforce, is that
the exhibited Python and C versions are NOT "exactly
the same algorithm", at least not without more quali-
fication. Part of Python expertise is to recognize
that creation of xrange objects, mentioned above, is
far from free. Also, -O3 gives C the opportunity,
also remarked in a follow-up, to factor calculations
outside their loops.
More information about the Python-list
mailing list