DAS_2024_1/yakovleva_yulia_lab_5/MultiplicationLargeMatrices/MultiplicationLargeMatrices/MatrixMultiplication.cs
2024-10-25 18:12:36 +04:00

57 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Threading.Tasks;
public class MatrixMultiplication
{
// Обычный метод умножения матриц
public static int[,] MultiplySequential(int[,] matrixA, int[,] matrixB)
{
int size = matrixA.GetLength(0);
int[,] result = new int[size, size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int sum = 0;
for (int k = 0; k < size; k++)
{
sum += matrixA[i, k] * matrixB[k, j];
}
result[i, j] = sum;
}
}
return result;
}
// Параллельный метод умножения матриц с заданием количества потоков
public static int[,] MultiplyParallel(int[,] matrixA, int[,] matrixB, int threadCount)
{
int size = matrixA.GetLength(0);
int[,] result = new int[size, size];
int chunkSize = size / threadCount;
Parallel.For(0, threadCount, threadIndex =>
{
int startRow = threadIndex * chunkSize;
int endRow = (threadIndex == threadCount - 1) ? size : startRow + chunkSize;
for (int i = startRow; i < endRow; i++)
{
for (int j = 0; j < size; j++)
{
int sum = 0;
for (int k = 0; k < size; k++)
{
sum += matrixA[i, k] * matrixB[k, j];
}
result[i, j] = sum;
}
}
});
return result;
}
}