import java.util.Random; class MatrixT { private final int rows; private final int cols; private final double[][] data; public MatrixT(int rows, int cols) { this.rows = rows; this.cols = cols; data = new double[rows][cols]; } public int Rows() { return rows; } public int Cols() { return cols; } public double get(int r, int c) { if (r < 0 || r >= rows || c < 0 || c >= cols) { throw new IndexOutOfBoundsException( "Index out of bounds: " + r + ", " + c); } return data[r][c]; } public void set(int r, int c, double value) { if (r < 0 || r >= rows || c < 0 || c >= cols) { throw new IndexOutOfBoundsException( "Index out of bounds: " + r + ", " + c); } data[r][c] = value; } public MatrixT multiply(MatrixT other) { if (cols != other.rows) { throw new IllegalArgumentException( "Matrix sizes don't match."); } MatrixT result = new MatrixT(rows, other.cols); for (int r = 0; r < rows; r++) { for (int c = 0; c < other.cols; c++) { for (int i = 0; i < other.rows; i++) { result.data[r][c] += data[r][i] * other.data[i][c]; } } } return result; } public void print() { for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { System.out.print(data[r][c] + " "); } System.out.println(); } } } public class MatrixBenchmark { private static final Random gen = new Random(); public static final int ROWS = 500; public static final int SAME = 300; public static final int COLS = 700; public static void MakeRandomMatrix(MatrixT m) { for (int r = 0; r < m.Rows(); r++) { for (int c = 0; c < m.Cols(); c++) { m.set(r, c, gen.nextDouble()); } } } public static void main(String[] args) { double totalTime = 0; System.out.println("Multiplying "+ ROWS + "X"+ SAME + " by "+ SAME+ "X"+ COLS); for (int i = 0; i < 10; i++) { long start = System.nanoTime(); MatrixT a = new MatrixT(ROWS, SAME); MatrixT b = new MatrixT(SAME, COLS); MakeRandomMatrix(a); MakeRandomMatrix(b); MatrixT c = a.multiply( b); long end = System.nanoTime(); double elapsed = (end - start) / 1_000_000_000.0; System.out.println("Time: " + elapsed + " seconds"); totalTime += elapsed; } System.out.println( "Average Time " + totalTime / 10 + " seconds"); } }