Skip to content

Commit

Permalink
добавил пример бенчмарка
Browse files Browse the repository at this point in the history
  • Loading branch information
lgnv committed Dec 8, 2024
1 parent 7f9c45a commit 1d57912
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions Testing/Advanced/Advanced.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="ApprovalTests" Version="6.0.0" />
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
<PackageReference Include="FakeItEasy" Version="8.3.0" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="log4net" Version="2.0.17" />
Expand Down
83 changes: 83 additions & 0 deletions Testing/Advanced/Samples/4. PerformanceTests/Benchmark.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
namespace Advanced.Samples.Performance;


using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
using FluentAssertions;
using NUnit.Framework;

[MemoryDiagnoser(true)]
public class Benchmarks
{
private const long num = long.MaxValue;

[Benchmark]
public void GetDigitsFromLeastSignificant_String()
{
num
.ToString()
.Select(x => Convert.ToByte(x.ToString()))
.ToArray();
}

[Benchmark]
public void GetDigitsFromLeastSignificant_MathWithSpan()
{
var result = new byte[20];
var span = new Span<byte>(result);
var n = num;
var index = 0;
while (n > 0)
{
span[index] = (byte)(n % 10);
n /= 10;
index++;
}

var res = span[..index].ToArray();
}

[Benchmark]
public void GetDigitsFromLeastSignificant_MathWithList()
{
var result = new List<byte>();
var n = num;
while (n > 0)
{
result.Add((byte)(n % 10));
n /= 10;
}
}

[Benchmark]
public void GetDigitsFromLeastSignificant_MathWithYield()
{
IEnumerable<byte> Inner()
{
var n = num;
while (n > 0)
{
yield return (byte)(n % 10);
n /= 10;
}
}

Inner().ToArray();
}
}

[TestFixture]
[Explicit]
public class BenchmarkTests
{
[Test]
public void GetDigitsFromLeastSignificant()
{
var config = ManualConfig
.CreateMinimumViable()
.WithOption(ConfigOptions.DisableOptimizationsValidator, true);

BenchmarkRunner.Run<Benchmarks>(config);
}
}

0 comments on commit 1d57912

Please sign in to comment.