Методы умножения матриц и векторов C#
Автор: Анна Синицина • Апрель 2, 2020 • Лабораторная работа • 4,006 Слов (17 Страниц) • 380 Просмотры
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace PPLab3
{
public class Parameters
{
public int X { get; private set; }
public int Y { get; private set; }
public int Z { get; private set; }
public int W { get; private set; }
public Parameters(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public Parameters(int x, int y, int z, int w):this(x,y,z)
{
W = w;
}
}
class MatrixMatrixSample
{
public int[,] matrixA { get; set; }
public int[,] matrixB { get; set; }
public int[,] result { get; set; }
public int minValue { get; set; } = 1;
public int maxValue { get; set; } = 5;
public int N { get; set; }
public int M { get; set; }
public int K { get; set; } = 3;
public int ThreadCount { get; set; } = 2;
public double ElapsedSeconds { get; set; }
public MatrixMatrixSample(int n, int m)
{
N = n;
M = m;
Fill();
}
public void MultiplyColumn()
{
result = new int[matrixA.GetLength(0), matrixB.GetLength(1)];
var sw = Stopwatch.StartNew();
for (int i = 0; i < matrixB.GetLength(1); i++)
for (int t = 0; t < matrixA.GetLength(0); t++)
for (int j = 0; j < matrixB.GetLength(0); j++)
result[t, i] += matrixA[t, j] * matrixB[j, i];
sw.Stop();
ElapsedSeconds = sw.Elapsed.TotalSeconds;
}
public void MultiplyColumnParallel()
{
var time = new List<double>();
for (int k = 0; k < K; k++)
{
result = new int[matrixA.GetLength(0), matrixB.GetLength(1)];
Thread[] threads = new Thread[ThreadCount];
var sw = Stopwatch.StartNew();
for (int n = 0; n < ThreadCount; n++)
{
threads[n] = new Thread(x => {
for (int i = (int)x; i < matrixB.GetLength(1); i += ThreadCount)
for (int t = 0; t < matrixA.GetLength(0); t++)
for (int j = 0; j < matrixB.GetLength(0); j++)
result[t, i] += matrixA[t, j] * matrixB[j, i];
});
threads[n].Start(n);
}
foreach (var thread in threads) thread.Join();
sw.Stop();
if (k > 0) time.Add(sw.Elapsed.TotalSeconds);
}
ElapsedSeconds = time.Average();
}
public void MultiplyFox()
{
result = new int[matrixA.GetLength(0), matrixB.GetLength(1)];
var q = 2;
var c = matrixA.GetLength(0) / q;
var sw = Stopwatch.StartNew();
for (int l = 0; l < q; l++)
{
for (int i = 0; i < q; i++)
{
var m = (i + l) % q;
for (int j = 0; j < q; j++)
MultiplyFox(i, j, m, c);
}
}
sw.Stop();
ElapsedSeconds
...