Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parallel matrix multiplication #1

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.x'
dotnet-version: '9.x'
- name: Build
run: for f in $(find . -name "*.sln"); do dotnet build $f; done
- name: Run tests
Expand All @@ -22,7 +22,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.x'
dotnet-version: '9.x'
- name: Build
run: For /R %%I in (*.sln) do dotnet build %%I
- name: Run tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
[*.cs]

# SA1010: Opening square brackets should be spaced correctly
dotnet_diagnostic.SA1010.severity = none

# Default severity for analyzer diagnostics with category 'StyleCop.CSharp.SpacingRules'
dotnet_analyzer_diagnostic.category-StyleCop.CSharp.SpacingRules.severity = none

[*.cs]
#### Стили именования ####

# Правила именования

dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i

dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case

dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case

# Спецификации символов

dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =

dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =

dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =

# Стили именования

dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case

dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
csharp_style_throw_expression = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_space_around_binary_operators = before_and_after
csharp_style_prefer_utf8_string_literals = true:suggestion

[*.vb]
#### Стили именования ####

# Правила именования

dotnet_naming_rule.interface_should_be_начинается_с_i.severity = suggestion
dotnet_naming_rule.interface_should_be_начинается_с_i.symbols = interface
dotnet_naming_rule.interface_should_be_начинается_с_i.style = начинается_с_i

dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.symbols = типы
dotnet_naming_rule.типы_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы

dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.severity = suggestion
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.symbols = не_являющиеся_полем_члены
dotnet_naming_rule.не_являющиеся_полем_члены_should_be_всечастиспрописнойбуквы.style = всечастиспрописнойбуквы

# Спецификации символов

dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.interface.required_modifiers =

dotnet_naming_symbols.типы.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.типы.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.типы.required_modifiers =

dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_kinds = property, event, method
dotnet_naming_symbols.не_являющиеся_полем_члены.applicable_accessibilities = public, friend, private, protected, protected_friend, private_protected
dotnet_naming_symbols.не_являющиеся_полем_члены.required_modifiers =

# Стили именования

dotnet_naming_style.начинается_с_i.required_prefix = I
dotnet_naming_style.начинается_с_i.required_suffix =
dotnet_naming_style.начинается_с_i.word_separator =
dotnet_naming_style.начинается_с_i.capitalization = pascal_case

dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case

dotnet_naming_style.всечастиспрописнойбуквы.required_prefix =
dotnet_naming_style.всечастиспрописнойбуквы.required_suffix =
dotnet_naming_style.всечастиспрописнойбуквы.word_separator =
dotnet_naming_style.всечастиспрописнойбуквы.capitalization = pascal_case

[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion
dotnet_style_namespace_match_folder = true:suggestion
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// <copyright file="IMatrixMultiplier.cs" company="IlyaSotnikov">
// Copyright (c) IlyaSotnikov. All rights reserved.
// </copyright>

namespace ParallelMatrixMultiplication;

/// <summary>
/// Interface for matrix multiplier.
/// </summary>
public interface IMatrixMultiplier
{
/// <summary>
/// The method for multiplication.
/// </summary>
/// <param name="inputMatrix1">First matrix.</param>
/// <param name="inputMatrix2">Second matrix.</param>
/// <returns>Result of multiplication.</returns>
/// <exception cref="ArgumentException">Throws if the matrices cannot be multiplied.</exception>
public int[][] Multiply(int[][] inputMatrix1, int[][] inputMatrix2);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// <copyright file="MatrixMultiplicationBenchmark.cs" company="IlyaSotnikov">
// Copyright (c) IlyaSotnikov. All rights reserved.
// </copyright>

namespace ParallelMatrixMultiplication;

using System.Diagnostics;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.ImageSharp;
using OxyPlot.Legends;
using OxyPlot.Series;

/// <summary>
/// Benchmark for parallel and sequence matrix multiplication.
/// </summary>
public class MatrixMultiplicationBenchmark
{
private static readonly Random Random = new ();
private readonly List<double> parallelTimesMeans = [];
private readonly List<double> sequentialTimesMeans = [];
private readonly List<int> sizes = [];

/// <summary>
/// The method to run the benchmark.
/// </summary>
/// <param name="size">Size of matrices.</param>
/// <param name="runs">A number of launches.</param>
public void Benchmark(int size, int runs)
{
int[][] matrix1 = GenerateMatrix(size);
int[][] matrix2 = GenerateMatrix(size);

var sequentialTimes = new double[runs];
var parallelTimes = new double[runs];

var sequentialMultiplier = new SequentialMultiplier();
var parallerMultiplier = new ParallelMultiplier();

Choose a reason for hiding this comment

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

Suggested change
var parallerMultiplier = new ParallelMultiplier();
var parallelMultiplier = new ParallelMultiplier();


for (int i = 0; i < runs; ++i)
{
var stopwatch = Stopwatch.StartNew();
sequentialMultiplier.Multiply(matrix1, matrix2);
stopwatch.Stop();
sequentialTimes[i] = stopwatch.Elapsed.TotalMilliseconds;

stopwatch.Restart();
parallerMultiplier.Multiply(matrix1, matrix2);
stopwatch.Stop();
parallelTimes[i] = stopwatch.Elapsed.TotalMilliseconds;
}

double sequentialMean = CalculateMean(sequentialTimes);
double parallelMean = CalculateMean(parallelTimes);
double sequentialStdDev = CalculateStandardDeviation(sequentialTimes, sequentialMean);
double parallelStdDev = CalculateStandardDeviation(parallelTimes, parallelMean);

this.sequentialTimesMeans.Add(sequentialMean);
this.parallelTimesMeans.Add(parallelMean);
this.sizes.Add(size);

Console.WriteLine($"Size: {size}, Sequential Mean: {sequentialMean} ms, Sequential StdDev: {sequentialStdDev} ms");
Console.WriteLine($"Size: {size}, Parallel Mean: {parallelMean} ms, Parallel StdDev: {parallelStdDev} ms\n");
}

/// <summary>
/// The method of plotting based on the results.
/// </summary>
public void MakeGraph()
{
var plotModel = new PlotModel
{
Title = "Performance graph",
Background = OxyColor.FromRgb(255, 255, 255),
};
plotModel.Legends.Add(new Legend { LegendTitle = "Legend", LegendPosition = LegendPosition.BottomRight });
plotModel.IsLegendVisible = true;

plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "Matrix sizes" });
plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Time (sec)" });

var sequentialSeries = new LineSeries { Title = "Sequential multiplication", MarkerType = MarkerType.Square };
for (int i = 0; i < this.sizes.Count; ++i)
{
sequentialSeries.Points.Add(new DataPoint(this.sizes[i], this.sequentialTimesMeans[i]));
}

plotModel.Series.Add(sequentialSeries);

var parallelSeries = new LineSeries { Title = "Parallel multiplication", MarkerType = MarkerType.Circle };
for (int i = 0; i < this.sizes.Count; ++i)
{
parallelSeries.Points.Add(new DataPoint(this.sizes[i], this.parallelTimesMeans[i]));
}

plotModel.Series.Add(parallelSeries);

var pngExporter = new PngExporter(800, 600, 96);
using (var stream = File.Create("graph.png"))
{
pngExporter.Export(plotModel, stream);
}

Console.WriteLine("The graph is saved as graph.png");
}

private static int[][] GenerateMatrix(int size)
{
var matrix = new int[size][];

for (int i = 0; i < size; ++i)
{
matrix[i] = new int[size];
for (int j = 0; j < size; ++j)
{
matrix[i][j] = Random.Next(1, 10);
}
}

return matrix;
}

private static double CalculateMean(double[] times)
{
double sum = 0;
foreach (var time in times)
{
sum += time;
}

return sum / times.Length;
}

private static double CalculateStandardDeviation(double[] times, double mean)
{
double sumOfSquares = 0;
foreach (var time in times)
{
sumOfSquares += Math.Pow(time - mean, 2);
}

return Math.Sqrt(sumOfSquares / times.Length);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<None Remove="stylecop.json" />
</ItemGroup>

<ItemGroup>
<AdditionalFiles Include="stylecop.json" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="OxyPlot.Core" Version="2.2.0" />
<PackageReference Include="OxyPlot.ImageSharp" Version="2.2.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34902.65
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ParallelMatrixMultiplication", "ParallelMatrixMultiplication.csproj", "{BFCB5A5A-9471-426A-9186-A3CE6B260FD0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ParallelMatrixMultiplicationTest", "..\ParallelMatrixMultiplicationTest\ParallelMatrixMultiplicationTest.csproj", "{AF5CD953-991A-4E1C-8D3D-9EE05476E7D5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BFCB5A5A-9471-426A-9186-A3CE6B260FD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BFCB5A5A-9471-426A-9186-A3CE6B260FD0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BFCB5A5A-9471-426A-9186-A3CE6B260FD0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BFCB5A5A-9471-426A-9186-A3CE6B260FD0}.Release|Any CPU.Build.0 = Release|Any CPU
{AF5CD953-991A-4E1C-8D3D-9EE05476E7D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF5CD953-991A-4E1C-8D3D-9EE05476E7D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF5CD953-991A-4E1C-8D3D-9EE05476E7D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF5CD953-991A-4E1C-8D3D-9EE05476E7D5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B5B8D1A9-B9DA-424A-A0FE-5AE8AD0E3F85}
EndGlobalSection
EndGlobal
Loading
Loading