Reply to post: Code efficiency

Moore's Law is deader than corduroy bell bottoms. But with a bit of smart coding it's not the end of the road

Stephen Davison

Code efficiency

Java's multidimensional arrays are more efficient when the reference to the inner array is cached. Without that, most the computation is the program trying to figure out where the data was stored in memory with modulo functions. The loop orders and values are also not very efficient unless the compiler is supposed to sort that out, which means that we're more measuring differences in compilers.

The following optimised Java version took 42.6s on one core. It would likely speed up the code in most the languages and remove the compiler as a factor.

Python gets a lot of its speed up from compiled C functions like sort() but this isn't in play when it does some basic looping so it looks very bad in an example like this.

int size = 4096;

double[][] A = new double[size][size];

double[][] B = new double[size][size];

double[][] C = new double[size][size];

for (int i = 0; i<size; i++) {

double[] asubarray = A[i];

double[] csubarray = C[i];

for (int k = 0; k<size; k++) {

double[] bsubarray = B[k];

double asubarrayValue = asubarray[k];

for (int j = 0; j<size; j++) {

csubarray[j] += asubarrayValue * bsubarray[j];

}

}

}

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon