[Tutor] Loop comparison
stefan_ml at behnel.de
Fri Apr 16 09:38:23 CEST 2010
Ark, 16.04.2010 08:50:
> A friend of mine suggested me to do the next experiment in python and Java.
> It's a simple program to sum all the numbers from 0 to 1000000000.
> result = i = 0
> while i< 1000000000:
> result += i
> i += 1
> print result
I hope you are aware that this is a) a very lousy benchmark and b) very
unidiomatic Python code.
> The time for this calculations was huge. It took a long time to give
> the result. But, the corresponding program in Java takes less than 1
> second to end. And if in Java, we make a simple type check per cycle,
> it does not take more than 10 seconds in the same machine. I was not
> expecting Python to be faster than Java, but it''s too slow. Maybe
> Java optimizes this case and Python doesn't. Not sure about this.}
Exactly. A compiler for a statically compiled language can see that the
above loop yields a constant result, so it can calculate the result in
advance (or at least reduce the loop overhead for the calculation) instead
of generating code for the loop as it stands.
The CPython runtime isn't particularly smart about arithmetic. You should
first put the above loop into a function, which will speed it up
considerably. Then, try the above code with psyco (a specialising JIT
compiler). Or give PyPy a try, which should also be pretty good in this.
You can also try to run the code through Cython, which is (more or less) a
Python compiler that supports static type annotations. You could write it
like this (which is also a much more pythonic implementation):
result = 0
for i in xrange(1000000000):
result += i
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
More information about the Tutor