Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Performance of Java math code vs. Python

807589Oct 21 2008 — edited Oct 21 2008
Hello,
Not to spark a religious war, but I'm curious: The November 2008 issue of Linux Journal has an article about Scientific Computing. In it, the author demonstrates how to use Python for doing number crunching. He compared Python to C. So I want to compare Python to Java.

I did this: created a file called matrix.py . Its contents are:
import numpy
a1=numpy.empty((500,500))
a2=numpy.empty((500,500))
a3=a1*a2
Then I ran it, by doing:
time python matrix.py
...on multiple occasions. I'm doing this on a Fedora 9 machine and figure it will buffer the disk read of the python interpreter. Anyway, it finishes in about 0.18 seconds (realtime).

Subsequently, I created a similar piece of Java code:
public class Test {
	public static void main(String args[]) {
		long start=System.currentTimeMillis();
		
		double a1[][]=new double[500][500];
		double a2[][]=new double[500][500];
		double a3[][]=new double[500][500];
		int i, j, k;

		for (i=0; i<500; i++) {
			for (j=0; j<500; j++) {
				a3[i][j]=0;
				for (k=0; k<500; k++) {
					a3[i][j] += a1[i][k] * a2[k][j];
				}
			}
		}
		long end=System.currentTimeMillis();
		end = end - start;
		System.out.println("Duration: " + end);
	}

}
...For Java, I didn't use time(1) to time the run, rather I used System.out.println from within the code. This is because I don't use Python so I didn't want to spend the time to learn how to do the time math as I did above, and also I figure that in everyday use the load time of the JVM would incur a startup penalty which I didn't want to measure. In short, I deliberately put Python at a disadvantage because I'm lazy. I figured I could learn a little Python and correct the issue if necessary.

Turns out, it's not necessary, because the Java code takes 1.5 seconds! That's 8-9 times slower than Python on this multiplication problem. What gives? Is Java just that slow? I thought that by this day and age it would be fairly optimized...

Thanks for the cluestick, in advance... :-)
-Hushpuppy
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 18 2008
Added on Oct 21 2008
10 comments
1,352 views