, , , - . , JVM , start stop , , , , , . JVM, JIT . GC . , JMH Caliper -.
JVM, . , Java 8 .
public class MatrixMultiplicationBenchmark {
private static AtomicLong start = new AtomicLong();
private static AtomicLong stop = new AtomicLong();
private static Random random = new Random();
public static void main(String[] args) {
System.out.println("Warming up...");
IntStream.range(0, 10_000_000).forEach(i -> run(10, MatrixMultiplicationBenchmark::multiplyWithStreams));
IntStream.range(0, 10_000_000).forEach(i -> run(10, MatrixMultiplicationBenchmark::multiplyWithForLoops));
startWatch("Running MatrixMultiplicationBenchmark::multiplyWithForLoops...");
IntStream.range(0, 10).forEach(i -> run(10_000_000, MatrixMultiplicationBenchmark::multiplyWithForLoops));
endWatch("MatrixMultiplicationBenchmark::multiplyWithForLoops");
startWatch("Running MatrixMultiplicationBenchmark::multiplyWithStreams...");
IntStream.range(0, 10).forEach(i -> run(10_000_000, MatrixMultiplicationBenchmark::multiplyWithStreams));
endWatch("MatrixMultiplicationBenchmark::multiplyWithStreams");
}
public static void run(int size, BiFunction<double[][], double[], double[]> multiplyImpl) {
double[][] matrix = new double[size][10];
double[] vector = random.doubles(10, 0.0, 10.0).toArray();
IntStream.range(0, size).forEach(i -> matrix[i] = random.doubles(10, 0.0, 10.0).toArray());
double[] result = multiplyImpl.apply(matrix, vector);
}
public static double[] multiplyWithStreams(final double[][] matrix, final double[] vector) {
final int rows = matrix.length;
final int columns = matrix[0].length;
return IntStream.range(0, rows)
.mapToDouble(row -> IntStream.range(0, columns)
.mapToDouble(col -> matrix[row][col] * vector[col])
.sum()).toArray();
}
public static double[] multiplyWithForLoops(double[][] matrix, double[] vector) {
int rows = matrix.length;
int columns = matrix[0].length;
double[] result = new double[rows];
for (int row = 0; row < rows; row++) {
double sum = 0;
for (int column = 0; column < columns; column++) {
sum += matrix[row][column] * vector[column];
}
result[row] = sum;
}
return result;
}
private static void startWatch(String label) {
System.out.println(label);
start.set(System.currentTimeMillis());
}
private static void endWatch(String label) {
stop.set(System.currentTimeMillis());
System.out.println(label + " took " + ((stop.longValue() - start.longValue()) / 1000) + "s");
}
}
Warming up...
Running MatrixMultiplicationBenchmark::multiplyWithForLoops...
MatrixMultiplicationBenchmark::multiplyWithForLoops took 100s
Running MatrixMultiplicationBenchmark::multiplyWithStreams...
MatrixMultiplicationBenchmark::multiplyWithStreams took 89s