Created
April 19, 2017 10:40
-
-
Save n-eq/8116fb7cd13d7d2dc492b80a332130ba to your computer and use it in GitHub Desktop.
Illustration of matrix transposition time performance effects due to cache configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MatrixTranspose { | |
public static void matrixTranspose(){ | |
long startTime, elapsedTime; | |
int n = 10000; | |
int a[][] = new int[n][n]; | |
int b[][] = new int[n][n]; | |
// ####################################### | |
for (int i = 0; i < n; i++){ | |
for (int j = 0; j < n; j++){ | |
a[i][j] = (int) (100 * Math.random()); | |
b[i][j] = (int) (100 * Math.random()); | |
} | |
} | |
System.out.print("Version 1 (iterative): "); | |
startTime = System.currentTimeMillis(); | |
for (int i = 0; i < n; i++){ | |
for (int j = 0; j < n; j++){ | |
b[i][j] = a[j][i]; | |
} | |
} | |
elapsedTime = System.currentTimeMillis() - startTime; | |
System.out.println("Elapsed time: " + elapsedTime + "ms."); | |
// ####################################### | |
for (int i = 0; i < n; i++){ | |
for (int j = 0; j < n; j++){ | |
a[i][j] = (int) (100 * Math.random()); | |
b[i][j] = (int) (100 * Math.random()); | |
} | |
} | |
System.out.print("Version 2 (iterative by block - K=10): "); | |
int K = 10; | |
startTime = System.currentTimeMillis(); | |
for (int I = 0; I < n; I += K){ | |
for (int J = 0; J < n; J += K){ | |
for (int i = K; i < Math.min(I + K, n); i++){ | |
for (int j = K; j < Math.min(J + K, n); j++){ | |
b[i][j] = a[j][i]; | |
} | |
} | |
} | |
} | |
elapsedTime = System.currentTimeMillis() - startTime; | |
System.out.println("Elapsed time: " + elapsedTime + "ms."); | |
} | |
public static void main(String args[]){ | |
matrixTanspose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment