tepechin_kirill_lab_5 #48
81
tepechin_kirill_lab_5/src/MatrixMultiply.java
Normal file
81
tepechin_kirill_lab_5/src/MatrixMultiply.java
Normal file
@ -0,0 +1,81 @@
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class MatrixMultiply {
|
||||
|
||||
public static int[][] generateMatrix(int n) {
|
||||
int[][] matrix = new int[n][n];
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
matrix[i][j] = (int) (Math.random() * 100);
|
||||
}
|
||||
}
|
||||
|
||||
return matrix;
|
||||
}
|
||||
|
||||
|
||||
private static int calculateSingleValue(int i, int j, int[][] a, int[][] b) {
|
||||
int result = 0;
|
||||
for (int k = 0; k < a[0].length; ++k) {
|
||||
result += a[i][k] * b[k][j];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static int[][] multiplySync(int[][] a, int[][] b) {
|
||||
final int[][] result = new int[a.length][b[0].length];
|
||||
for (int i = 0; i < a.length; ++i) {
|
||||
for (int j = 0; j < b[0].length; ++j) {
|
||||
result[i][j] = calculateSingleValue(i, j, a, b);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int[][] multiplyAsync(int[][] a, int[][] b, ExecutorService executor) throws InterruptedException {
|
||||
final int[][] result = new int[a.length][b[0].length];
|
||||
for (int i = 0; i < a.length; ++i) {
|
||||
final int fi = i;
|
||||
executor.execute(() -> {
|
||||
for (int j = 0; j < b[0].length; ++j) {
|
||||
for (int k = 0; k < a[0].length; ++k) {
|
||||
result[fi][j] += a[fi][k] * b[k][j];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
executor.shutdown();
|
||||
executor.awaitTermination(1, TimeUnit.DAYS);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
run(100);
|
||||
run(300);
|
||||
run(500);
|
||||
}
|
||||
|
||||
public static void run(int n) throws InterruptedException {
|
||||
System.out.println("N = " + n);
|
||||
final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
|
||||
|
||||
final int[][] a = generateMatrix(n);
|
||||
final int[][] b = generateMatrix(n);
|
||||
|
||||
long time = System.currentTimeMillis();
|
||||
final int[][] productSync = multiplySync(a, b);
|
||||
System.out.println("Time sync: " + (System.currentTimeMillis() - time));
|
||||
|
||||
time = System.currentTimeMillis();
|
||||
final int[][] productAsync = multiplyAsync(a, b, executorService);
|
||||
System.out.println("Time async: " + (System.currentTimeMillis() - time));
|
||||
System.out.println();
|
||||
|
||||
// System.out.println(Arrays.deepEquals(productAsync, productSync));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user