diff --git a/.gitignore b/.gitignore index c6127b3..72de34f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,52 +1,388 @@ -# Prerequisites -*.d +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore -# Object files -*.o -*.ko -*.obj -*.elf +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates -# Linker output -*.ilk -*.map -*.exp +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs -# Precompiled Headers -*.gch -*.pch +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch *.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Nuget personal access tokens and Credentials +nuget.config + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf +# JetBrains Rider +.idea/ +*.sln.iml \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/EmptyFileTest.txt b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/EmptyFileTest.txt new file mode 100644 index 0000000..e69de29 diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/FileFunctionsTest.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/FileFunctionsTest.cs new file mode 100644 index 0000000..650fd12 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/FileFunctionsTest.cs @@ -0,0 +1,32 @@ +using NUnit.Framework; + +namespace ParallelMatrixMultiplication.Test +{ + public class FileFunctionTest + { + [Test] + public void TestNormalFilePath() + { + int[,] result = + { + {2, 1, 2}, + {4, 1, 5}, + {1, 5, 3} + }; + var resultFromFile = FunctionsForFile.CreateMatrix("../../../MatrixTest1.txt"); + Assert.AreEqual(result, resultFromFile); + } + + [Test] + public void TestAbnormalFilePath() + { + Assert.Throws(() => FunctionsForFile.CreateMatrix(null)); + } + + [Test] + public void TestEmptyFile() + { + Assert.Throws(() => FunctionsForFile.CreateMatrix("../../../EmptyFileTest.txt")); + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixFunctionTest.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixFunctionTest.cs new file mode 100644 index 0000000..fc3139e --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixFunctionTest.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using NUnit.Framework; + +namespace ParallelMatrixMultiplication.Test +{ + public class MatrixFunctionTest + { + [TestCaseSource(nameof(FunctionsForTest))] + public void TestNormalSquareData(Func multiplication) + { + int[,] result = + { + {15, 27, 8}, + {24, 57, 13}, + {41, 26, 24} + }; + int[,] matrix1 = + { + {2, 1, 2}, + {4, 1, 5}, + {1, 5, 3} + }; + int[,] matrix2 = + { + {3, 9, 1}, + {7, 1, 4}, + {1, 4, 1} + }; + var matrix = multiplication(matrix1, matrix2); + Assert.AreEqual(result, matrix); + } + + [TestCaseSource(nameof(FunctionsForTest))] + public void TestNormalNotSquareData(Func multiplication) + { + int[,] result = + { + {36, 71, 29}, + {30, 22, 23}, + {49, 87, 28} + }; + int[,] matrix1 = + { + {6, 1, 3, 4}, + {1, 3, 2, 2}, + {7, 3, 5, 1} + }; + int[,] matrix2 = + { + {3, 9, 1}, + {7, 1, 4}, + {1, 4, 1}, + {2, 1, 4} + }; + var matrix = multiplication(matrix1, matrix2); + Assert.AreEqual(result, matrix); + } + + [TestCaseSource(nameof(FunctionsForTest))] + public void TestAbnormalData(Func multiplication) + { + var matrix1 = new int[3, 4]; + var matrix2 = new int[3, 3]; + Assert.Throws(() => multiplication(matrix1, matrix2)); + } + + private static IEnumerable> FunctionsForTest() + { + yield return MatrixFunctions.MatrixMultiplicationParallel; + yield return MatrixFunctions.MatrixMultiplication; + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixTest1.txt b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixTest1.txt new file mode 100644 index 0000000..3436bd2 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/MatrixTest1.txt @@ -0,0 +1,3 @@ +2 1 2 +4 1 5 +1 5 3 \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/ParallelMatrixMultiplication.Test.csproj b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/ParallelMatrixMultiplication.Test.csproj new file mode 100644 index 0000000..0954619 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.Test/ParallelMatrixMultiplication.Test.csproj @@ -0,0 +1,20 @@ + + + + net5.0 + + false + + + + + + + + + + + + + + diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication.sln b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.sln new file mode 100644 index 0000000..f7de292 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31624.102 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ParallelMatrixMultiplication", "ParallelMatrixMultiplication\ParallelMatrixMultiplication.csproj", "{A8AF63A3-1364-4FA2-8832-D27A339FAD1B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ParallelMatrixMultiplication.Test", "ParallelMatrixMultiplication.Test\ParallelMatrixMultiplication.Test.csproj", "{A569F36C-B06B-4DE2-AC6A-0A26D8C140A1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A8AF63A3-1364-4FA2-8832-D27A339FAD1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A8AF63A3-1364-4FA2-8832-D27A339FAD1B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A8AF63A3-1364-4FA2-8832-D27A339FAD1B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A8AF63A3-1364-4FA2-8832-D27A339FAD1B}.Release|Any CPU.Build.0 = Release|Any CPU + {A569F36C-B06B-4DE2-AC6A-0A26D8C140A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A569F36C-B06B-4DE2-AC6A-0A26D8C140A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A569F36C-B06B-4DE2-AC6A-0A26D8C140A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A569F36C-B06B-4DE2-AC6A-0A26D8C140A1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3EC4E190-8ABB-4682-A8B2-190BAE5FEFB0} + EndGlobalSection +EndGlobal diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/EmptyFileException.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/EmptyFileException.cs new file mode 100644 index 0000000..752432e --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/EmptyFileException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ParallelMatrixMultiplication +{ + /// + /// then file is empty + /// + public class EmptyFileException : Exception + { + public EmptyFileException() + { + } + + public EmptyFileException(string message) + : base(message) + { + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/FunctionsForFile.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/FunctionsForFile.cs new file mode 100644 index 0000000..999c19a --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/FunctionsForFile.cs @@ -0,0 +1,98 @@ +using System; +using System.IO; + +namespace ParallelMatrixMultiplication +{ + /// + /// Functions for working with files + /// + public static class FunctionsForFile + { + private static void CheckFilePath(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + throw new WrongFilePathException("File path is incorrect!"); + } + } + + private static (int, int) CountMatrixSize(string filePath) + { + CheckFilePath(filePath); + using var file = new StreamReader(filePath); + string line = file.ReadLine(); + int size = 0; + if (string.IsNullOrEmpty(line)) + { + throw new EmptyFileException("File is empty!"); + } + + string[] lineDrop = line.Split(" ", StringSplitOptions.RemoveEmptyEntries); + while (line != null) + { + size++; + line = file.ReadLine(); + } + + return (size, lineDrop.Length); + } + + /// + /// Create Matrix from file + /// + public static int[,] CreateMatrix(string filePath) + { + CheckFilePath(filePath); + (int length, int width) size = CountMatrixSize(filePath); + var matrix = new int[size.length, size.width]; + using var file = new StreamReader(filePath); + string line = file.ReadLine(); + var index = 0; + while (line != null) + { + string[] lineDrop = line.Split(" ", StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < size.length; ++i) + { + matrix[index, i] = Int32.Parse(lineDrop[i]); + } + + index++; + line = file.ReadLine(); + } + + return matrix; + } + + /// + /// Create file and return matrix + /// + public static void CreateFileWithMatrix(string filePath, int[,] matrix) + { + CheckFilePath(filePath); + var fileOut = new FileInfo(filePath); + if (fileOut.Exists) + { + fileOut.Delete(); + } + + using var newFile = new FileStream(filePath, FileMode.Create); + using var file = new StreamWriter(newFile); + for (int i = 0; i < matrix.GetLength(0); i++) + { + string line = ""; + for (int j = 0; j < matrix.GetLength(1); j++) + { + line += $"{matrix[i, j]} "; + } + + file.WriteLine(line); + } + + file.Close(); + if (fileOut.Exists) + { + fileOut.MoveTo(filePath); + } + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix1.txt b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix1.txt new file mode 100644 index 0000000..5b041e1 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix1.txt @@ -0,0 +1,3 @@ +2 1 2 +4 1 5 +1 5 3 \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix2.txt b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix2.txt new file mode 100644 index 0000000..66c58cb --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Matrix2.txt @@ -0,0 +1,3 @@ +9 3 1 +4 6 9 +1 5 7 \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MatrixFunctions.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MatrixFunctions.cs new file mode 100644 index 0000000..4691052 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MatrixFunctions.cs @@ -0,0 +1,85 @@ +using System; +using System.Threading; + +namespace ParallelMatrixMultiplication +{ + /// + /// Class with matrix multiplication + /// + public static class MatrixFunctions + { + /// + /// Parallel matrix multiplication + /// + public static int[,] MatrixMultiplicationParallel(int[,] matrix1, int[,] matrix2) + { + if (matrix1.GetLength(1) != matrix2.GetLength(0)) + { + throw new MultiplicationException( + "Number of columns in the first matrix are not equal to the rows in the second matrix!"); + } + + var matrix = new int[matrix1.GetLength(0), matrix2.GetLength(1)]; + var size = matrix1.GetLength(0) < Environment.ProcessorCount + ? matrix1.GetLength(0) + : Environment.ProcessorCount; + var threads = new Thread[size]; + var chunkSize = matrix.GetLength(0) / threads.Length + 1; + for (int i = 0; i < threads.Length; ++i) + { + var localI = i; + threads[i] = new Thread(() => + { + for (var l = localI * chunkSize; l < (localI + 1) * chunkSize && l < matrix1.GetLength(0); ++l) + { + for (int j = 0; j < matrix2.GetLength(1); j++) + { + for (int k = 0; k < matrix1.GetLength((1)); k++) + { + matrix[l, j] += matrix1[l, k] * matrix2[k, j]; + } + } + } + }); + } + + foreach (var thread in threads) + { + thread.Start(); + } + + foreach (var thread in threads) + { + thread.Join(); + } + + return matrix; + } + + /// + /// Not parallel matrix multiplication + /// + public static int[,] MatrixMultiplication(int[,] matrix1, int[,] matrix2) + { + if (matrix1.GetLength(1) != matrix2.GetLength(0)) + { + throw new MultiplicationException( + "Number of columns in the first matrix are not equal to the rows in the second matrix!"); + } + + var matrix = new int[matrix1.GetLength(0), matrix2.GetLength(1)]; + for (int i = 0; i < matrix1.GetLength(0); i++) + { + for (int j = 0; j < matrix2.GetLength(1); j++) + { + for (int k = 0; k < matrix1.GetLength((1)); k++) + { + matrix[i, j] += matrix1[i, k] * matrix2[k, j]; + } + } + } + + return matrix; + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MultiplicationException.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MultiplicationException.cs new file mode 100644 index 0000000..6ab9fb9 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/MultiplicationException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ParallelMatrixMultiplication +{ + /// + /// then matrices cannott be multiplied + /// + public class MultiplicationException : Exception + { + public MultiplicationException() + { + } + + public MultiplicationException(string message) + : base(message) + { + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/ParallelMatrixMultiplication.csproj b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/ParallelMatrixMultiplication.csproj new file mode 100644 index 0000000..2082704 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/ParallelMatrixMultiplication.csproj @@ -0,0 +1,8 @@ + + + + Exe + net5.0 + + + diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Program.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Program.cs new file mode 100644 index 0000000..d1478c1 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Program.cs @@ -0,0 +1,53 @@ +using System; +using System.Diagnostics; +using System.Threading; + +namespace ParallelMatrixMultiplication +{ + class Program + { + static void Main(string[] args) + { + Statistics.CollectStatisticsFromMatrix(128, 128, 100); + /* + Результаты на матрицах размеров 128*128. + Количество повторов: 100. + Паралельное умножение: + Матожидание = 13,75 ms + Среднеквадратичное отклонение = 3,89 ms + Обычное умножение: + Матожидание = 37,86 ms + Среднеквадратичное отклонение = 9,04 ms + */ + + Statistics.CollectStatisticsFromMatrix(256, 256, 100); + /* + Результаты на матрицах размеров 256*256. + Количество повторов: 100. + Паралельное умножение: + Матожидание = 72,4 ms + Среднеквадратичное отклонение = 10,58 ms + Обычное умножение: + Матожидание = 169,91 ms + Среднеквадратичное отклонение = 20,95 ms + */ + + Statistics.CollectStatisticsFromMatrix(512, 512, 100); + /* + Результаты на матрицах размеров 512*512. + Количество повторов: 100. + Паралельное умножение: + Матожидание = 602,98 ms + Среднеквадратичное отклонение = 39,31 ms + Обычное умножение: + Матожидание = 2049,14 ms + Среднеквадратичное отклонение = 361,01 ms + */ + + var matrixFirst = FunctionsForFile.CreateMatrix(args[0]); + var matrixSecond = FunctionsForFile.CreateMatrix(args[1]); + var matrix = MatrixFunctions.MatrixMultiplicationParallel(matrixFirst, matrixSecond); + FunctionsForFile.CreateFileWithMatrix(args[2], matrix); + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Statistics.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Statistics.cs new file mode 100644 index 0000000..9cd5b91 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/Statistics.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace ParallelMatrixMultiplication +{ + /// + /// class for collecting statistics + /// + public class Statistics + { + /// + /// Collect statistics from matrix + /// + public static void CollectStatisticsFromMatrix(int row, int column, int count) + { + (var timeParallel, var timeNotParallel) = GetTimeMatrixMultiplication(count, row, column); + var result = GetStatistics(timeParallel, timeNotParallel); + Console.WriteLine($"Результаты на матрицах размеров {row}*{column}."); + Console.WriteLine($"Количество повторов: {count}."); + Console.WriteLine("Паралельное умножение:"); + Console.WriteLine( + $"Матожидание = {result[0].average}\nСреднеквадратичное отклонение = {result[0].standardDeviation}"); + Console.WriteLine("Обычное умножение:"); + Console.WriteLine( + $"Матожидание = {result[1].average}\nСреднеквадратичное отклонение = {result[1].standardDeviation}"); + } + + private static (double average, double standardDeviation)[] GetStatistics(List timeParallel, + List timeNotParallel) + { + var averageParallel = timeParallel.Average(); + var averageNotParallel = timeNotParallel.Average(); + var dispersionParallel = timeParallel.Select(x => Math.Pow(x - averageParallel, 2)).Average(); + var dispersionNotParallel = timeNotParallel.Select(x => Math.Pow(x - averageNotParallel, 2)).Average(); + var standardDeviationParallel = Math.Sqrt(dispersionParallel); + var standardDeviationNotParallel = Math.Sqrt(dispersionNotParallel); + var results = new (double, double)[2]; + results[0] = (averageParallel, standardDeviationParallel); + results[1] = (averageNotParallel, standardDeviationNotParallel); + return results; + } + + private static (List, List) GetTimeMatrixMultiplication(int count, int countRows, int countColumns) + { + var timeParallel = new List(); + var timeNotParallel = new List(); + var timer = new Stopwatch(); + for (int i = 0; i < count; i++) + { + var matrix1 = GenerateMatrix(countRows, countColumns); + var matrix2 = GenerateMatrix(countRows, countColumns); + timer.Restart(); + MatrixFunctions.MatrixMultiplicationParallel(matrix1, matrix2); + timer.Stop(); + timeParallel.Add(timer.ElapsedMilliseconds); + timer.Restart(); + MatrixFunctions.MatrixMultiplication(matrix1, matrix2); + timer.Stop(); + timeNotParallel.Add(timer.ElapsedMilliseconds); + } + + return (timeParallel, timeNotParallel); + } + + private static int[,] GenerateMatrix(int countRow, int countColumns) + { + var matrix = new int[countRow, countColumns]; + var random = new Random(); + for (int i = 0; i < countRow; i++) + { + for (int j = 0; j < countColumns; j++) + { + matrix[i, j] = random.Next(0, 100); + } + } + + return matrix; + } + } +} \ No newline at end of file diff --git a/ParallelMatrixMultiplication/ParallelMatrixMultiplication/WrongFilePathException.cs b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/WrongFilePathException.cs new file mode 100644 index 0000000..6a55306 --- /dev/null +++ b/ParallelMatrixMultiplication/ParallelMatrixMultiplication/WrongFilePathException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ParallelMatrixMultiplication +{ + public class WrongFilePathException : Exception + { + /// + /// then filePath is abnormal + /// + public WrongFilePathException() + { + } + + public WrongFilePathException(string message) + : base(message) + { + } + } +} \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..9809100 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,3 @@ +build_script: +- For /R %%I in (*.sln) do dotnet test %%I +test: of \ No newline at end of file