[Tutor] Loop comparison

Christian Witts cwitts at compuscan.co.za
Fri Apr 16 10:46:03 CEST 2010

Alan Gauld wrote:
> "Stefan Behnel" <stefan_ml at behnel.de> wrote
>>     import cython
>>     @cython.locals(result=cython.longlong, i=cython.longlong)
>>     def add():
>>         result = 0
>>         for i in xrange(1000000000):
>>             result += i
>>         return result
>>     print add()
>> This runs in less than half a second on my machine, including the 
>> time to launch the CPython interpreter. I doubt that the JVM can even 
>> start up in that time.
> I'm astonished at these results. What kind of C are you using. Even in 
> assembler I'd expect the loop/sum to take at least 3s
> on a quad core 3GHz box.
> Or is cython doing the precalculation optimisations you mentioned?
> And if so when does it do them? Because surely, at some stage, it 
> still has to crank the numbers?
> (We can of course do some fancy math to speed this particular sum up 
> since the result for any power of ten has a common pattern, but I 
> wouldn't expect the compiler optimiser to be that clever)

The precalculation optimisations are taking place.  If you pass it an 
argument to use for the upper limit of the sequence the calculation time 
shoots up.

Kind Regards,
Christian Witts

More information about the Tutor mailing list