Skip to content

Параллельное умножение матриц#20

Open
Palezehvat wants to merge 7 commits intomasterfrom
parallelMatrixMultiplication
Open

Параллельное умножение матриц#20
Palezehvat wants to merge 7 commits intomasterfrom
parallelMatrixMultiplication

Conversation

@Palezehvat
Copy link
Owner

No description provided.

Copy link

@YuriUfimtsev YuriUfimtsev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отсутствие метода последовательного умножения матриц и сравнения с параллельным вариантом. Надо дополнить.

/// The function calculates the mathematical expectation and the standard deviation
/// </summary>
/// <param name="filePath">The file where the results are recorded</param>
public static void CreateTableWithResults(string filePath)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Файл с результатами стоит тоже подгрузить

/// <summary>
/// Exception for errors with file
/// </summary>
public class InvalidFileException : Exception{} No newline at end of file

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Конструкторов маловато, хотя бы один должен быть

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем конструкторы, если они наследуются от Exception, разве нет?

Copy link

@YuriUfimtsev YuriUfimtsev Sep 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем, исключение базовых классов не "наследуются" (иначе бы мы могли написать new InvalidFileException("Error message")), но "вызываются" для дочернего класса. Неявно вызываются без параметров.

И сейчас у дочернего класса InvalidFileException тоже есть конструктор по умолчанию без параметров, который выполняется последним среди всей цепочки конструкторов.
Поэтому, конечно, с точки зрения компилируемости и работоспособности кода всё хорошо. Но идеологически, если мы создаём свой exception, то подразумеваем, что оно всеми свойствами исключений обладает: и сообщения передаёт, и внутренние исключения. Поэтому определение конструкторов и входит в exceptions best practices: https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions.
Хотя на практике конструктор с innerException часто опускается

/// <summary>
/// A function that receives files with matrices at the input, and a calculated matrix at the output
/// </summary>
public static void MatrixMultiplicationControlFunction(string firstFile, string secondFile, string resultFile, int sizeThreads)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тот же MatrixMultiplication для "файловых" матриц. Стоит оформить как перегрузку метода MatrixMultiplication

/// <returns>Returns the created matrix</returns>
/// <exception cref="ArgumentException">Throws an exception if the number of items
/// in the list does not match the size of the matrix</exception>
public static int[][] CreateMatrix(int sizeRows, int sizeColumns, List<int> numbersForMatrix)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно ли здесь слово Matrix? Или пользователь по названию класса сориентируется

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ввод данных через список? А если я ввел значения матрицы 100 * 4 и хочу себя перепроверить. Придется глазами отделять по 4 числа, а где-нибудь к середине вообще случится непреднамеренное смещение на пару чисел. И это еще хорошо, если подряд не будет десятка одинаковых чисел.
Так что нагляднее и дружелюбнее будет списком списков / массивов передавать значения

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Скорее эта функция создавалась для тестов и не предполагалась для пользователя, ну если надо и для пользователя, то ок, исправлю

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, надо исправить, потому что даже для тестов лучше делать визуально понятнее для упрощения как самопроверки, так и проверки другими людьми

/// <summary>
/// The function compares matrices
/// </summary>
public static bool MatrixComparison(int[][] firstMatrix, int[][] secondMatrix)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тот же вопрос по Matrix. И методы лучше глаголами именовать. Здесь, например, Compare

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще метод Compare имеет немного другой смысл. Он возвращает число: 0 - объекты равны, x > 0 - первый объект (в каком-то смысле) больше, x < 0 - второй объект больше.
В вашем случае вы просто сравниваете объекты на равенство, поэтому метод лучше назвать AreMatricesEquals

/// </summary>
/// <returns>Returns the calculated matrix</returns>
public static int[][] MatrixMultiplication(int[][] firstMatrix, int[][] secondMatrix, int threadCounts)
{

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Перекладывать на пользователя ответственность за количество потоков, конечно, можно. Но обрадуется ли он, если введет 5, а на самом деле свободно 6 (Environment.ProccesorCount вернет 6), и один поток будет простаивать (а пользователь скучать лишние n минут). Или если введет 50, ожидая, что заварит чай и увидит результат умножения огромных матриц, а просидит еще дольше, потому что доступных потоков будет сильно меньше, и его 50 штук будут толпиться, забирая время на переключение между потоками.
Так что если стремимся к эффективности и меньшему ожиданию результата, то число потоков надо брать из Environment.ProcessorCount

Comment on lines 155 to 159
var allLines = File.ReadAllLines(filePath);

var matrix = new int[allLines.Length][];

var sizeColumns = 0;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
var allLines = File.ReadAllLines(filePath);
var matrix = new int[allLines.Length][];
var sizeColumns = 0;
var allLines = File.ReadAllLines(filePath);
var matrix = new int[allLines.Length][];
var sizeColumns = 0;

start = end;
}

foreach (var thread in threads )

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
foreach (var thread in threads )
foreach (var thread in threads)

/// <summary>
/// A class for measuring the standard deviation and mathematical expectation
/// </summary>
public static class CreateTable

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так все-таки класс для измерения отклонения и ожидания или для создания таблиц? :)

Console.WriteLine("Write file path for create table");
var tableFile = Console.ReadLine();

if (tableFile != null && firstFile != null && secondFile != null && resultFile != null)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стоит сообщать о результате: записалось в файл / не записалось (и в чем тогда проблема)

/// A class for measuring the standard deviation and mathematical expectation
/// </summary>
public static class CreateTable
public static class GetStandartDeviationAndMinValue
Copy link

@YuriUfimtsev YuriUfimtsev Sep 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Файл тоже надо переименовать. И лучше классы называть существительными, "StandartDeviationAndMathExpectationMeasurements"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, MinValue хорошо бы поменять в коде на MathExpectation (или объяснить, если это не одно и то же)

@@ -0,0 +1,13 @@
В файле представлены: математическое ожидание и среднеквадратичное отклонение
Copy link

@YuriUfimtsev YuriUfimtsev Sep 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так лучше, но все равно стоит привести к виду, который просили по условию.

  1. Показательнее привести результаты для достаточно больших размеров матриц (например, брать минимальный размер 500x500)
  2. Файл преобразовать в табличный вид

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что имеется в виду под табличным видом? И есть же отдельный пример для больших матриц: 10000x10000 и 10000x1

Copy link

@YuriUfimtsev YuriUfimtsev Oct 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Табличный вид: сверху названия величин, ниже результаты измерений. Самый простой способ: текстовый файл с разделителями для ячеек таблицы, либо с аккуратным выравниванием.

Один пример для больших матриц есть, надо больше, см. условие.

}
if (resultFile == null)
{
Console.WriteLine("Неверно прописан путь для firstFile");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

для resultFile

}
if (firstFile == null)
{
Console.WriteLine("Неверно прописан путь для resultFile");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

firstFile

Comment on lines 226 to 230
listOfValuesSecondMatrix.Add(new int[1] { 1 });
listOfValuesSecondMatrix.Add(new int[1] { 2 });
listOfValuesSecondMatrix.Add(new int[1] { 0 });
listOfValuesSecondMatrix.Add(new int[1] { 0 });
listOfValuesSecondMatrix.Add(new int[1] { 5 });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно проще (здесь и в других местах)

Suggested change
listOfValuesSecondMatrix.Add(new int[1] { 1 });
listOfValuesSecondMatrix.Add(new int[1] { 2 });
listOfValuesSecondMatrix.Add(new int[1] { 0 });
listOfValuesSecondMatrix.Add(new int[1] { 0 });
listOfValuesSecondMatrix.Add(new int[1] { 5 });
var listOfValuesSecondMatrix = new List<int[]>
{
new int[1] { 1 },
new int[1] { 2 },
new int[1] { 0 },
new int[1] { 0 },
new int[1] { 5 },
}

}

private static void MultiplyingMatricesWithNegativeNumbers(string filePath)
{

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Private-методы лучше тоже глаголами именовать. MultiplyMatricesWithNegativeNumbers (и соседние методы аналогично)

return resultMatrix;
}

private static int[][] ConvertinMatrixToTransposedOne(int[][] matrix)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ConvertMatrixToTransposedOne

/// <returns>Returns the created matrix</returns>
/// <exception cref="ArgumentException">Throws an exception if the number of items
/// in the list does not match the size of the matrix</exception>
public static int[][] Create(int sizeRows, int sizeColumns, List<int[]> numbersForMatrix)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот, Matrix.Create гораздо приятнее читается :)
Ниже тоже можно без Matrix в названиях методов обходиться

stopWatch.Start();
var resultMatrix = Matrix.Multiply(firstMatrix, secondMatrix);
stopWatch.Stop();
arrayForStandardDeviation[i] = (double)stopWatch.ElapsedMilliseconds / 1000;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем здесь на тысячу деление?

@@ -0,0 +1,13 @@
В файле представлены: математическое ожидание и среднеквадратичное отклонение
Математическое ожидание и среднеквадратичное отклонение для матриц размера 3x3:
Матемматическое ожидание: 0,0019000000000000002 Среднеквадратичное отклонение: 0,002514402955419481

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Матемматическое ожидание: 0,0019000000000000002 Среднеквадратичное отклонение: 0,002514402955419481
Математическое ожидание: 0,0019000000000000002 Среднеквадратичное отклонение: 0,002514402955419481

@@ -0,0 +1,13 @@
В файле представлены: математическое ожидание и среднеквадратичное отклонение
Copy link

@YuriUfimtsev YuriUfimtsev Oct 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Табличный вид: сверху названия величин, ниже результаты измерений. Самый простой способ: текстовый файл с разделителями для ячеек таблицы, либо с аккуратным выравниванием.

Один пример для больших матриц есть, надо больше, см. условие.

нулями 0,1 0,3162278

500x500
и 500x500 106,3 4,6916001
Copy link

@YuriUfimtsev YuriUfimtsev Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, хотя бы с двумя примерами для больших матриц.
Также надо разделить результаты (матожидание и отклонение) на параллельный и последовательный варианты: то, ради чего эти все измерения затевались.
А измерения для маленьких матриц лучше вообще убрать: непоказательно, так еще и среднеквадратичное отклонение больше матожидания

Copy link

@YuriUfimtsev YuriUfimtsev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошо, но пару вещей поправить осталось


500x500
и 500x500 129,5 29,9007618 614,8 7,4654761

Copy link

@YuriUfimtsev YuriUfimtsev Oct 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Столбец с матожиданием под размеры матриц уехал, и названия друг под другом сидят. Можно их как-нибудь сократить, например, английский язык использовать или греческие буквы, общепринятые для этих величин.
А с длинными фразами про параллельность и последовательность можно так поступить: текст на строке "параллельный метод умножения", ниже все данные, включая размеры, ниже строчка с объявлением последовательного способа и снова все данные в ячейках.
Важно, чтобы значения друг к другу не липли, и названия столбцов хотя бы на расстоянии одного пробела друг от друга находились
image

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я не знаю, где вы открываете файл или смотрите его, однако у меня нету переноса 3 и др длинных строк в обычном блокноте просто обычные строки, хоть и большой длины, так стоят ли так сильно заморачиваться с таблицей если только github или там где вы открывали, переносит строчки? Кроме того при запуске программы сгенерится txt'шник, который можно открыть в блокноте и там всё будет ок.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В любом случае, при незначительном уменьшении окна значения таблицы файла не должны так сильно съезжать. Что если у пользователя другое разрешение экрана? Он будет вынужден анализировать ваш съехавший файл

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок, я понял, исправлю. Однако в коде нет переносов строки, которые ломают таблицу, значит переносит либо текстовый редактор, либо у пользователя выставлено сильное приближение экрана, так разве неважно насколько небольшие столбцы, найдётся пользователь у которого всё равно будет съехавшая таблица, почему мы не можем переложить вину на пользователя в этом случае?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошо, давайте просто добьемся того, чтобы при открытии файла на весь экран все выглядело хорошо: под каждым названием было свое значение, названия друг на друга не наезжали, и далее в каждой (одной) строке находилось по 5 значений.
Ключевая проблема того, что у вас сейчас даже при просмотре в полноэкранном режиме название одного столбца съезжает, и значения скачут по разным строчкам в том, что у вас сильно много табуляций стоит между значениями, и названия столбцов длинные. Поменяйте это и всё должно стать хорошо :)

var correctMatrix = Matrix.Create(3, 3, listOfCorrectValues);

var resultMatrix = Matrix.Multiply(firstMatrix, secondMatrix);
Assert.True(Matrix.AreEquals(resultMatrix, correctMatrix));
Copy link

@YuriUfimtsev YuriUfimtsev Oct 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Еще у вас в тестах не заметил сравнения результатов последовательного умножения CoherentMultiply с параллельным (который почему-то просто Multiply, лучше тогда тоже ParallelMultiply назвать).
Так что добавьте, пожалуйста, проверки в тестах на то, что другой метод умножения тот же результат дает

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

Comments