Merge pull request 'emelyanov_artem_lab_6' (#77) from emelyanov_artem_lab_6 into main
Reviewed-on: #77
This commit is contained in:
commit
7e09109cd2
27
emelyanov_artem_lab_6/Benchmark.java
Normal file
27
emelyanov_artem_lab_6/Benchmark.java
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
public class Benchmark {
|
||||||
|
public static void main(String[] args) throws ExecutionException, InterruptedException {
|
||||||
|
int[] sizes = {5, 7, 10};
|
||||||
|
|
||||||
|
for (int size : sizes) {
|
||||||
|
int[][] matrix = MatrixGenerator.generateMatrix(size);
|
||||||
|
|
||||||
|
// Последовательное вычисление
|
||||||
|
long startSequential = System.nanoTime();
|
||||||
|
double detSequential = DeterminantCalculator.calculateDeterminant(matrix, 1);
|
||||||
|
long endSequential = System.nanoTime();
|
||||||
|
System.out.println("Последовательно (" + size + "x" + size + "): " + (endSequential - startSequential) / 1_000_000 + " ms, детерминант: " + detSequential);
|
||||||
|
|
||||||
|
// Параллельное вычисление
|
||||||
|
for (int numThreads : new int[]{2, 4, 8}) {
|
||||||
|
long startParallel = System.nanoTime();
|
||||||
|
double detParallel = DeterminantCalculator.calculateDeterminant(matrix, numThreads);
|
||||||
|
long endParallel = System.nanoTime();
|
||||||
|
System.out.println("Параллельно (" + size + "x" + size + ", " + numThreads + " потоков): " +
|
||||||
|
(endParallel - startParallel) / 1_000_000 + " ms, детерминант: " + detParallel);
|
||||||
|
}
|
||||||
|
System.out.println("--------------------------------------------------");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
80
emelyanov_artem_lab_6/DeterminantCalculator.java
Normal file
80
emelyanov_artem_lab_6/DeterminantCalculator.java
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
public class DeterminantCalculator {
|
||||||
|
public static int calculateDeterminant(int[][] matrix, int numThreads) throws InterruptedException, ExecutionException {
|
||||||
|
int size = matrix.length;
|
||||||
|
|
||||||
|
// Если размер матрицы 1x1, возвращаем единственный элемент.
|
||||||
|
if (size == 1) {
|
||||||
|
return matrix[0][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если количество потоков равно 1, выполняем последовательный алгоритм.
|
||||||
|
if (numThreads == 1) {
|
||||||
|
return sequentialDeterminant(matrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Иначе выполняем параллельный алгоритм.
|
||||||
|
return parallelDeterminant(matrix, numThreads);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int sequentialDeterminant(int[][] matrix) {
|
||||||
|
int size = matrix.length;
|
||||||
|
if (size == 1) {
|
||||||
|
return matrix[0][0];
|
||||||
|
}
|
||||||
|
if (size == 2) {
|
||||||
|
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
int determinant = 0;
|
||||||
|
for (int col = 0; col < size; col++) {
|
||||||
|
determinant += (int) (Math.pow(-1, col) * matrix[0][col] * sequentialDeterminant(getMinor(matrix, 0, col)));
|
||||||
|
}
|
||||||
|
return determinant;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int parallelDeterminant(int[][] matrix, int numThreads) throws InterruptedException, ExecutionException {
|
||||||
|
int size = matrix.length;
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
|
||||||
|
List<Future<Double>> futures = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int col = 0; col < size; col++) {
|
||||||
|
int finalCol = col;
|
||||||
|
futures.add(executor.submit(() -> {
|
||||||
|
double minorDet = sequentialDeterminant(getMinor(matrix, 0, finalCol));
|
||||||
|
return Math.pow(-1, finalCol) * matrix[0][finalCol] * minorDet;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
int determinant = 0;
|
||||||
|
for (Future<Double> future : futures) {
|
||||||
|
determinant += future.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.shutdown();
|
||||||
|
return determinant;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[][] getMinor(int[][] matrix, int row, int col) {
|
||||||
|
int size = matrix.length;
|
||||||
|
int[][] minor = new int[size - 1][size - 1];
|
||||||
|
|
||||||
|
for (int i = 0, mi = 0; i < size; i++) {
|
||||||
|
if (i == row) continue;
|
||||||
|
for (int j = 0, mj = 0; j < size; j++) {
|
||||||
|
if (j == col) continue;
|
||||||
|
minor[mi][mj] = matrix[i][j];
|
||||||
|
mj++;
|
||||||
|
}
|
||||||
|
mi++;
|
||||||
|
}
|
||||||
|
return minor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
11
emelyanov_artem_lab_6/MatrixGenerator.java
Normal file
11
emelyanov_artem_lab_6/MatrixGenerator.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
public class MatrixGenerator {
|
||||||
|
public static int[][] generateMatrix(int size) {
|
||||||
|
int[][] matrix = new int[size][size];
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
for (int j = 0; j < size; j++) {
|
||||||
|
matrix[i][j] = (int) (Math.random() * 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
}
|
12
emelyanov_artem_lab_6/Readme.md
Normal file
12
emelyanov_artem_lab_6/Readme.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
# Поиск детерминанта
|
||||||
|
|
||||||
|
Данная работа посвящена реализации и сравнению последовательного и параллельного алгоритмов поиска детерминанта матриц на языке Java. Целью является оценка производительности при использовании разного числа потоков.
|
||||||
|
|
||||||
|
## Результаты:
|
||||||
|
|
||||||
|
![img.png](images/img.png)
|
||||||
|
|
||||||
|
Как видим, однозначно сказать нельзя, для маленьких матриц многопоточность особо не повлияла. Начиная с матрицы размерностью 10, есть прибавка в производительности. Посмотрим на сложность алгоритма, и она будет что-то около O(n!), так как алгоритм рекурсивный.
|
||||||
|
Для больших матриц, типа 100 на 100, сложность будет огромной, и не думаю что такое получится посчитать.
|
||||||
|
|
||||||
|
Ссылка на видео: https://drive.google.com/file/d/1eCNcSLLLfWGlOk5Z0y0CfOfkbxeASrdE/view?usp=sharing
|
BIN
emelyanov_artem_lab_6/images/img.png
Normal file
BIN
emelyanov_artem_lab_6/images/img.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 49 KiB |
BIN
emelyanov_artem_lab_6/img.png
Normal file
BIN
emelyanov_artem_lab_6/img.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 49 KiB |
80
emelyanov_artem_lab_7/.idea/workspace.xml
Normal file
80
emelyanov_artem_lab_7/.idea/workspace.xml
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AutoImportSettings">
|
||||||
|
<option name="autoReloadType" value="SELECTIVE" />
|
||||||
|
</component>
|
||||||
|
<component name="ChangeListManager">
|
||||||
|
<list default="true" id="ece3d3db-34eb-42c6-9dfd-726739d49f9f" name="Changes" comment="feature: completed lab 7" />
|
||||||
|
<option name="SHOW_DIALOG" value="false" />
|
||||||
|
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||||
|
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||||
|
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||||
|
</component>
|
||||||
|
<component name="Git.Settings">
|
||||||
|
<option name="RECENT_BRANCH_BY_REPOSITORY">
|
||||||
|
<map>
|
||||||
|
<entry key="$PROJECT_DIR$/.." value="emelyanov_artem_lab_7" />
|
||||||
|
</map>
|
||||||
|
</option>
|
||||||
|
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectColorInfo"><![CDATA[{
|
||||||
|
"associatedIndex": 4
|
||||||
|
}]]></component>
|
||||||
|
<component name="ProjectId" id="2nes6IK0Z3YgtIz3E1743Ralffw" />
|
||||||
|
<component name="ProjectViewState">
|
||||||
|
<option name="hideEmptyMiddlePackages" value="true" />
|
||||||
|
<option name="showLibraryContents" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="PropertiesComponent"><![CDATA[{
|
||||||
|
"keyToString": {
|
||||||
|
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||||
|
"git-widget-placeholder": "emelyanov__artem__lab__6",
|
||||||
|
"kotlin-language-version-configured": "true",
|
||||||
|
"last_opened_file_path": "/home/forever/УлГТУ/Распределенные вычисления и приложения/DAS_2024_1/emelyanov_artem_lab_7",
|
||||||
|
"node.js.detected.package.eslint": "true",
|
||||||
|
"node.js.detected.package.tslint": "true",
|
||||||
|
"node.js.selected.package.eslint": "(autodetect)",
|
||||||
|
"node.js.selected.package.tslint": "(autodetect)",
|
||||||
|
"nodejs_package_manager_path": "npm",
|
||||||
|
"settings.editor.selected.configurable": "preferences.keymap",
|
||||||
|
"vue.rearranger.settings.migration": "true"
|
||||||
|
}
|
||||||
|
}]]></component>
|
||||||
|
<component name="SharedIndexes">
|
||||||
|
<attachedChunks>
|
||||||
|
<set>
|
||||||
|
<option value="bundled-jdk-9823dce3aa75-28b599e66164-intellij.indexing.shared.core-IU-242.22855.74" />
|
||||||
|
<option value="bundled-js-predefined-d6986cc7102b-5c90d61e3bab-JavaScript-IU-242.22855.74" />
|
||||||
|
</set>
|
||||||
|
</attachedChunks>
|
||||||
|
</component>
|
||||||
|
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||||
|
<component name="TaskManager">
|
||||||
|
<task active="true" id="Default" summary="Default task">
|
||||||
|
<changelist id="ece3d3db-34eb-42c6-9dfd-726739d49f9f" name="Changes" comment="" />
|
||||||
|
<created>1729344698203</created>
|
||||||
|
<option name="number" value="Default" />
|
||||||
|
<option name="presentableId" value="Default" />
|
||||||
|
<updated>1729344698203</updated>
|
||||||
|
<workItem from="1729344699237" duration="1655000" />
|
||||||
|
</task>
|
||||||
|
<task id="LOCAL-00001" summary="feature: completed lab 7">
|
||||||
|
<option name="closed" value="true" />
|
||||||
|
<created>1729346451585</created>
|
||||||
|
<option name="number" value="00001" />
|
||||||
|
<option name="presentableId" value="LOCAL-00001" />
|
||||||
|
<option name="project" value="LOCAL" />
|
||||||
|
<updated>1729346451585</updated>
|
||||||
|
</task>
|
||||||
|
<option name="localTasksCounter" value="2" />
|
||||||
|
<servers />
|
||||||
|
</component>
|
||||||
|
<component name="TypeScriptGeneratedFilesManager">
|
||||||
|
<option name="version" value="3" />
|
||||||
|
</component>
|
||||||
|
<component name="VcsManagerConfiguration">
|
||||||
|
<MESSAGE value="feature: completed lab 7" />
|
||||||
|
<option name="LAST_COMMIT_MESSAGE" value="feature: completed lab 7" />
|
||||||
|
</component>
|
||||||
|
</project>
|
Loading…
Reference in New Issue
Block a user