[Tutor] Loop comparison
alan.gauld at btinternet.com
Fri Apr 16 10:29:40 CEST 2010
"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)
Author of the Learn to Program web site
More information about the Tutor