优化原理:CPU缓存机制
1 import java.util.Random; 2 3 public class MatrixCalculate { 4 public static void main(String[] args) { 5 int size = 2000; 6 float[][] m1 = new float[size][size]; 7 float[][] m2 = new float[size][size]; 8 randomFill(m1); 9 randomFill(m2); 10 11 //m1·m2 12 float[][] result1 = new float[size][size]; 13 long start = System.currentTimeMillis(); 14 for (int i = 0; i < size; i++) { 15 for (int k = 0; k < size; k++) { 16 for (int j = 0; j < size; j++) { 17 result1[i][j] += m1[i][k] * m2[k][j]; 18 } 19 } 20 } 21 System.out.println("耗时:" + (System.currentTimeMillis() - start)); 22 float[][] result2 = new float[size][size]; 23 start = System.currentTimeMillis(); 24 for (int i = 0; i < size; i++) { 25 for (int j = 0; j < size; j++) { 26 for (int k = 0; k < size; k++) { 27 result2[i][j] += m1[i][k] * m2[k][j]; 28 } 29 } 30 } 31 System.out.println("耗时:" + (System.currentTimeMillis() - start)); 32 for (int i = 0; i < size; i++) { 33 for (int j = 0; j < size; j++) { 34 if (result1[i][j] != result2[i][j]) { 35 System.out.println("======ERROR===="); 36 System.out.println(result1[i][j]); 37 System.out.println(result2[i][j]); 38 } 39 } 40 } 41 } 42 43 public static void randomFill(float[][] floats) { 44 for (int i = 0; i < floats.length; i++) { 45 for (int j = 0; j < floats[i].length; j++) { 46 floats[i][j] = new Random().nextFloat(); 47 } 48 } 49 } 50 }