[Tutor] Loop comparison

Alan Gauld alan.gauld at btinternet.com
Fri Apr 16 10:09:23 CEST 2010

"Ark" <cloudneozero at gmail.com> wrote 

> 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
> 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.  

That's astonishing, it implies your PC is running at around 20GHz!
I want one! :-)

But Python will always be much slower for this kind of thing since Pythons 
integers are very different to Java ints (BTW did Java returtn an int or 
a float result?) Using something like psycho should yield a big improvement 
I suspect. Also some of the math libraries may have a native C summing 
function for large arrays. Even the built in sum() will be faster than a while 

result = sum(range(1000000000))

although it still took 10 minutes on my PC.

> And if in Java, we make a simple type check per cycle,
> it does not take more than 10 seconds in the same machine.  

That would be more like the kind of figure I'd expect.
Remember the time increases exponentialy. In my tests Python 
was sub 1s up to 10**7 then 10s for 10**8 and 600s for 10**9 )
Memory speed will play a big role here too since Pythons storage 
of large integers requires a lot of memory allocating/deallocating
compared to Java which uses native CPU integers

> I was not expecting Python to be faster than Java, but it''s too slow.  

For this kind of task yes. It was never designed for high speed 
number crunching. Thats why dedicated math modules have been 
written in C.

> Java optimizes this case and Python doesn't.  Not sure about this.}

The approaches are completely different. Java uses native ints, 
Python  uses arbitrarily long ints. Java's JVM will map closely 
to native CPU operations, Python is effectively calling functions.
This is almost a pathalogical case for comparing the two languages.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list