1 Commits

Author SHA1 Message Date
0c1493a9d9 laba done 2023-12-16 16:41:40 +04:00
30 changed files with 603 additions and 322 deletions

View File

@@ -0,0 +1,87 @@
# Отчет по лабораторной работе №3
Выполнила студентка гр. ИСЭбд-41 Зиновьева А. Д.
## REST API, Gateway и синхронный обмен между микросервисами
## Создание микросервисов
1. Создала первый микросервис - `dotnet new web -n worker-1`
2. Добавила решение - `dotnet new sln`
3. Связала решение и проект - `dotnet sln worker-1.sln add worker-1.csproj`
4. Для второго микросервиса выполнила пункты 1-3
5. Добавила библиотеку Swagger и OpenAi - `dotnet add worker-1.csproj package Swashbuckle.AspNetCore` , `dotnet add worker-1.csproj package Microsoft.AspNetCore.OpenApi`
6. Запустила - `dotnet run`
Скриншоты протестированных микросервисов:
![](pic/Screenshot_5.jpg)
![](pic/Screenshot_6.jpg)
## Реализация синхронного обмена
Код реализации синхронного обмена:
```cs
//Файл Program.cs проекта worker-2
app.MapGet("/Requests/", async () =>
{
var httpClient = new HttpClient();
var secondWorkerResponse = await httpClient.GetStringAsync("http://worker-1:8080/");
return secondWorkerResponse.ToArray();
})
.WithName("GetRequests")
.WithOpenApi();
```
## Реализация gateway при помощи nginx
Добавила nginx.conf:
```conf
server {
listen 8080;
listen [::]:8080;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /worker-1/ {
proxy_pass http://worker-1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /worker-1;
}
location /worker-2/ {
proxy_pass http://worker-2:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /worker-2;
}
}
```
Результат, после выполнения команды `docker compose up`:
Docker:
![](pic/Screenshot_3.jpg)
index.html на gateway-1:
![](pic/Screenshot_4.jpg)
worker-1:
![](pic/Screenshot_1.jpg)
worker-2:
![](pic/Screenshot_2.jpg)

View File

@@ -0,0 +1,15 @@
version: "3.1"
services:
worker-1:
build: ./worker-1
worker-2:
build: ./worker-2
depends_on:
- worker-1
gateway:
image: nginx:latest
ports:
- 8080:8080
volumes:
- ./static:/usr/share/nginx/html:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro

View File

@@ -0,0 +1,26 @@
server {
listen 8080;
listen [::]:8080;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /worker-1/ {
proxy_pass http://worker-1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /worker-1;
}
location /worker-2/ {
proxy_pass http://worker-2:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /worker-2;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тестовое приложение для л/р 3</title>
</head>
<body>
<p>Зиновьева Анна Дмитриевна, группа ИСЭбд-41.</p>
<p><a href="/worker-1/">Отправить запрос к worker-1</a></p>
<p><a href="/worker-2/">Отправить запрос к worker-2</a></p>
</body>
</html>

View File

@@ -0,0 +1,11 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env
WORKDIR /app
COPY . ./
RUN dotnet restore
RUN dotnet publish -c Release -o out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "worker-1.dll"]

View File

@@ -0,0 +1,124 @@
List<Request> requests = new()
{
new Request() { Uuid= Guid.Parse("7777fa5f-b786-4478-863a-99cc000eb752"), Title = "Документ (прием на работу)", DateDocument = new DateTime(2023, 8, 05), Employee = "Иванов Иван Иванович", IsAgreed = false },
new Request() { Uuid= Guid.Parse("77a9aed1-218a-468e-92b9-99f6a6a34543"), Title = "Документ (увольнение)", DateDocument = new DateTime(2023, 8, 05), Employee = "Петров Петр Петрович", IsAgreed = true },
};
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/", () =>
{
return requests.Select(r => new RequestEntityDto()
{
Uuid = r.Uuid,
Title = r.Title,
DateDocument = r.DateDocument,
Employee = r.Employee,
IsAgreed = r.IsAgreed,
});
})
.WithName("GetRequests")
.WithOpenApi();
app.MapGet("/{uuid}", (Guid uuid) =>
{
var request = requests.FirstOrDefault(r => r.Uuid == uuid);
if (request == null)
return Results.NotFound();
return Results.Json(new RequestEntityDto()
{
Uuid = request.Uuid,
Title = request.Title,
DateDocument = request.DateDocument,
Employee = request.Employee,
IsAgreed = request.IsAgreed,
});
})
.WithName("GetRequestByGUID")
.WithOpenApi();
app.MapPost("/{title}/{Employee}/{DateDocument}/{IsAgreed}", (string title, string Employee, DateTime DateDocument, bool IsAgreed) =>
{
Guid NewGuid = Guid.NewGuid();
requests.Add(new Request() { Uuid = NewGuid, Title = (string)title, Employee = (string)Employee, DateDocument = (DateTime)DateDocument, IsAgreed = (bool)IsAgreed});
var request = requests.FirstOrDefault(r => r.Uuid == NewGuid);
if (request == null)
return Results.NotFound();
return Results.Json(new RequestEntityDto()
{
Uuid = request.Uuid,
Title = request.Title,
DateDocument = request.DateDocument,
Employee = request.Employee,
IsAgreed = request.IsAgreed,
});
})
.WithName("PostRequest")
.WithOpenApi();
app.MapPatch("/{uuid}/{title}/{Employee}/{DateDocument}/{IsAgreed}", (Guid uuid, string? title, string? Employee, DateTime DateDocument, bool IsAgreed) =>
{
var request = requests.FirstOrDefault(r => r.Uuid == uuid);
if (request == null)
return Results.NotFound();
if (title != null) request.Title = title;
if (Employee != ",") request.Employee = Employee;
if (DateDocument != request.DateDocument) request.DateDocument = DateDocument;
if (IsAgreed != request.IsAgreed) request.IsAgreed = IsAgreed;
return Results.Json(new RequestEntityDto()
{
Uuid = request.Uuid,
Title = request.Title,
DateDocument = request.DateDocument,
Employee = request.Employee,
IsAgreed = request.IsAgreed,
});
})
.WithName("UpdateRequest")
.WithOpenApi();
app.MapDelete("/{uuid}", (Guid uuid) =>
{
var request = requests.FirstOrDefault(r => r.Uuid == uuid);
if (request == null)
return Results.NotFound();
requests.Remove(request);
return Results.Json(new RequestEntityDto()
{
Uuid = request.Uuid,
Title = request.Title,
DateDocument = request.DateDocument,
Employee = request.Employee,
IsAgreed = request.IsAgreed,
});
})
.WithName("DeleteRequestByGUID")
.WithOpenApi();
app.Run();
public class Request
{
public Guid Uuid { get; set; }
public string Title { get; set; } = string.Empty;
public string Employee { get; set; } = string.Empty;
public DateTime DateDocument { get; set; }
public bool IsAgreed { get; set; }
}
public class RequestEntityDto : Request { }

View File

@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:26412",
"sslPort": 44362
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5068",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7253;http://localhost:5068",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>worker_1</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "worker-1", "worker-1.csproj", "{A28AE5F5-3B71-480C-A9A2-899D2286584A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A28AE5F5-3B71-480C-A9A2-899D2286584A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A28AE5F5-3B71-480C-A9A2-899D2286584A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A28AE5F5-3B71-480C-A9A2-899D2286584A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A28AE5F5-3B71-480C-A9A2-899D2286584A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,11 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env
WORKDIR /app
COPY . ./
RUN dotnet restore
RUN dotnet publish -c Release -o out
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "worker-2.dll"]

View File

@@ -0,0 +1,132 @@
List<Agreement> agrs = new()
{
new Agreement() { Uuid= Guid.NewGuid(), Number = "242697-03К", IdRequest = Guid.Parse("7777fa5f-b786-4478-863a-99cc000eb752") }
};
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapGet("/", () =>
{
return agrs.Select(r => new AgreementEntityDto()
{
Uuid = r.Uuid,
Number = r.Number,
IdRequest = r.IdRequest,
});
})
.WithName("GetAgreements")
.WithOpenApi();
app.MapGet("/{uuid}", (Guid uuid) =>
{
var agr = agrs.FirstOrDefault(r => r.Uuid == uuid);
if (agr == null)
return Results.NotFound();
return Results.Json(new AgreementEntityDto()
{
Uuid = agr.Uuid,
Number = agr.Number,
IdRequest = agr.IdRequest,
});
})
.WithName("GetAgreementByGUID")
.WithOpenApi();
app.MapPost("/{number}/{idRequest}", (string? number, Guid idRequest) =>
{
Guid NewGuid = Guid.NewGuid();
agrs.Add(new Agreement() { Uuid = NewGuid, Number = (string)number, IdRequest = (Guid)idRequest });
var agr = agrs.FirstOrDefault(r => r.Uuid == NewGuid);
if (agr == null)
return Results.NotFound();
return Results.Json(new AgreementEntityDto()
{
Uuid = agr.Uuid,
Number = agr.Number,
IdRequest = agr.IdRequest,
});
})
.WithName("PostAgreement")
.WithOpenApi();
app.MapPatch("/{uuid}/{number}/{idRequest}", (Guid uuid, string ?number, Guid idRequest) =>
{
var agr = agrs.FirstOrDefault(r => r.Uuid == uuid);
if (agr == null)
return Results.NotFound();
if (number != ",") agr.Number = number;
if (idRequest != agr.IdRequest) agr.IdRequest = idRequest;
return Results.Json(new AgreementEntityDto()
{
Uuid = agr.Uuid,
Number = agr.Number,
IdRequest = agr.IdRequest,
});
})
.WithName("UpdateAgreement")
.WithOpenApi();
app.MapDelete("/{uuid}", (Guid uuid) =>
{
var agr = agrs.FirstOrDefault(r => r.Uuid == uuid);
if (agr == null)
return Results.NotFound();
agrs.Remove(agr);
return Results.Json(new AgreementEntityDto()
{
Uuid = agr.Uuid,
Number = agr.Number,
IdRequest = agr.IdRequest,
});
})
.WithName("DeleteAgreement")
.WithOpenApi();
app.MapGet("/Requests/", async () =>
{
var httpClient = new HttpClient();
var secondWorkerResponse = await httpClient.GetStringAsync("http://worker-1:8080/");
return secondWorkerResponse.ToArray();
})
.WithName("GetRequests")
.WithOpenApi();
app.Run();
public class Agreement
{
public Guid Uuid { get; set; }
public string Number { get; set; } = string.Empty;
public Guid IdRequest { get; set; }
}
public class AgreementEntityDto : Agreement { }
public class Request
{
public Guid Uuid { get; set; }
public string Title { get; set; } = string.Empty;
public string Employee { get; set; } = string.Empty;
public DateTime DateDocument { get; set; }
public bool IsAgreed { get; set; }
}
public class RequestEntityDto : Request { }

View File

@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:26693",
"sslPort": 44348
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5011",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7162;http://localhost:5011",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>worker_2</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "worker-2", "worker-2.csproj", "{F7FA965A-55AB-476E-9A6C-DFA7603EB733}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F7FA965A-55AB-476E-9A6C-DFA7603EB733}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7FA965A-55AB-476E-9A6C-DFA7603EB733}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7FA965A-55AB-476E-9A6C-DFA7603EB733}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F7FA965A-55AB-476E-9A6C-DFA7603EB733}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -1,72 +0,0 @@
# Отчет по лабораторной работе №6
Выполнила студентка гр. ИСЭбд-41 Зиновьева А. Д.
## Создание приложения
Было выбрано консольное приложение, язык программирования - c#.
Обычный алгоритм:
```cs
static double CalculateDeterminantSequential(int[,] matrix)
{
int size = matrix.GetLength(0);
double determinant = 0;
if (size == 1)
{
determinant = matrix[0, 0];
}
else if (size == 2)
{
determinant = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
for (int j = 0; j < size; j++)
{
determinant += matrix[0, j] * CalculateMinor(matrix, 0, j) * Math.Pow(-1, j);
}
}
return determinant;
}
```
Параллельный алгоритм:
```cs
static double CalculateDeterminantParallel(int[,] matrix, int threads)
{
int size = matrix.GetLength(0);
double determinant = 0;
if (size == 1)
{
determinant = matrix[0, 0];
}
else if (size == 2)
{
determinant = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
Parallel.For(0, size, new ParallelOptions { MaxDegreeOfParallelism = threads }, j =>
{
determinant += matrix[0, j] * CalculateMinor(matrix, 0, j) * Math.Pow(-1, j);
});
}
return determinant;
}
```
## Бенчмарки
Для примера была взята матрица размерностью 10х10, поскольку для матриц больших размеров детерминант вычисляется слишком долго.
![](pic/pic1.jpg)
``Вывод``: Обычный (последовательный) алгоритм работает быстрее, если количество элементов не слишком много. Параллельный же алгоритм работает быстрее только при наличии большого количества операций и данных.

View File

@@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleAppLab6", "ConsoleAppLab6\ConsoleAppLab6.csproj", "{BB915677-B73E-45C7-85DD-F66D7FC9E97E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BB915677-B73E-45C7-85DD-F66D7FC9E97E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB915677-B73E-45C7-85DD-F66D7FC9E97E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB915677-B73E-45C7-85DD-F66D7FC9E97E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB915677-B73E-45C7-85DD-F66D7FC9E97E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {20D650BB-330E-48AD-8607-6220061D9FDE}
EndGlobalSection
EndGlobal

View File

@@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -1,215 +0,0 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Выберите задание для выполнения:");
//Console.WriteLine("1 - Нахождение детерминанта квадратной матрицы");
Console.WriteLine("2 - Бенчмарки");
string choice = Console.ReadLine();
if (choice == "1")
{
//int threads = GetNumberOfThreads(); // Запрашиваем количество потоков у пользователя
//int matrixSize = 10; // Размер матрицы
//int[,] matrixA = GenerateRandomMatrix(matrixSize);
//int[,] matrixB = GenerateRandomMatrix(matrixSize);
//Console.WriteLine("Выполняется обычное умножение матриц...");
//Stopwatch stopwatch = Stopwatch.StartNew();
//int[,] result1 = MultiplyMatrices(matrixA, matrixB, matrixSize);
//stopwatch.Stop();
//Console.WriteLine($"Результат (обычное умножение матриц): \n {GetMatrixString(result1)}");
//Console.WriteLine($"Время выполнения: {stopwatch.Elapsed.TotalSeconds} секунд \n");
//Console.WriteLine("Выполняется параллельное умножение матриц...");
//stopwatch.Restart();
//int[,] result2 = ParallelMultiplyMatrices(matrixA, matrixB, matrixSize, threads);
//stopwatch.Stop();
//Console.WriteLine($"Результат (параллельное умножение матриц): \n {GetMatrixString(result2)}");
//Console.WriteLine($"Время выполнения: {stopwatch.Elapsed.TotalSeconds} секунд \n");
//Console.WriteLine("\nНажмите Enter, чтобы вернуться в главное меню...");
//Console.ReadLine();
}
else if (choice == "2")
{
int threads = GetNumberOfThreads(); // Запрашиваем количество потоков у пользователя
Console.WriteLine("\nВыполнение алгоритма по нахождению детерминанта квадратной матрицы размером 10x10:");
RunDeterminantBenchmark(10, threads);
Console.ReadLine();
}
else
{
Console.WriteLine("Некорректный выбор.");
Console.WriteLine("\nНажмите Enter, чтобы вернуться в главное меню...");
Console.ReadLine();
}
Console.ReadLine();
}
static void RunDeterminantBenchmark(int size, int threads)
{
int[,] matrix = GenerateRandomMatrix(size);
Console.WriteLine("Исходная матрица:");
GetMatrixString(matrix);
Stopwatch stopwatch = Stopwatch.StartNew();
stopwatch.Restart();
double sequentialDeterminant = CalculateDeterminantSequential(matrix);
stopwatch.Stop();
Console.WriteLine($"Последовательное выполнение: детерминант = {sequentialDeterminant}, время выполнения = {stopwatch.Elapsed.TotalSeconds} секунд");
stopwatch.Restart();
double parallelDeterminant = CalculateDeterminantParallel(matrix, threads);
stopwatch.Stop();
Console.WriteLine($"Параллельное выполнение: детерминант = {parallelDeterminant}, время выполнения = {stopwatch.Elapsed.TotalSeconds} секунд");
}
static int[,] GenerateRandomMatrix(int size)
{
Random random = new Random();
int[,] matrix = new int[size, size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
matrix[i, j] = random.Next(10);
}
}
return matrix;
}
static double CalculateDeterminantSequential(int[,] matrix)
{
int size = matrix.GetLength(0);
double determinant = 0;
if (size == 1)
{
determinant = matrix[0, 0];
}
else if (size == 2)
{
determinant = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
for (int j = 0; j < size; j++)
{
determinant += matrix[0, j] * CalculateMinor(matrix, 0, j) * Math.Pow(-1, j);
}
}
return determinant;
}
static double CalculateDeterminantParallel(int[,] matrix, int threads)
{
int size = matrix.GetLength(0);
double determinant = 0;
if (size == 1)
{
determinant = matrix[0, 0];
}
else if (size == 2)
{
determinant = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0];
}
else
{
Parallel.For(0, size, new ParallelOptions { MaxDegreeOfParallelism = threads }, j =>
{
determinant += matrix[0, j] * CalculateMinor(matrix, 0, j) * Math.Pow(-1, j);
});
}
return determinant;
}
static double CalculateMinor(int[,] matrix, int row, int col)
{
int size = matrix.GetLength(0);
int[,] minor = new int[size - 1, size - 1];
int minorRow = 0;
for (int i = 0; i < size; i++)
{
if (i == row)
{
continue;
}
int minorCol = 0;
for (int j = 0; j < size; j++)
{
if (j == col)
{
continue;
}
minor[minorRow, minorCol] = matrix[i, j];
minorCol++;
}
minorRow++;
}
return CalculateDeterminantSequential(minor);
}
static double MeasureExecutionTime(Action action)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
return stopwatch.Elapsed.TotalSeconds;
}
static int GetNumberOfThreads()
{
int threads = 1;
Console.WriteLine("Введите количество потоков:");
int.TryParse(Console.ReadLine(), out threads);
return threads;
}
static void PrintMatrix(int[,] matrix)
{
int size = matrix.GetLength(0);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
static string GetMatrixString(int[,] matrix)
{
int rows = matrix.GetLength(0);
int columns = matrix.GetLength(1);
string matrixString = "";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
matrixString += matrix[i, j] + " ";
}
matrixString += "\n";
}
return matrixString;
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB