Skip to content

Instantly share code, notes, and snippets.

@MonkAlex
Created March 31, 2024 22:26
Show Gist options
  • Save MonkAlex/3ee81313728b3b7227a8a223f64973c3 to your computer and use it in GitHub Desktop.
Save MonkAlex/3ee81313728b3b7227a8a223f64973c3 to your computer and use it in GitHub Desktop.
habr 803273 example
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Threading;
public static class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<Bench>();
}
[ThreadingDiagnoser]
public class Bench
{
[Params(10, 100, 1000, 10_000)]
public int Repeat;
[Benchmark]
public void Lock()
{
var a = new Lock();
for (int i = 0; i < Repeat; i++)
{
a.SomeMethod();
}
a.Assert(Repeat);
}
[Benchmark]
public void QueueExample()
{
var a = new SerialQueueExample();
for (int i = 0; i < Repeat; i++)
{
a.SomeMethod();
}
a.Assert(Repeat);
}
}
class Lock
{
readonly object locker = new object();
private int counter = 0;
public void SomeMethod()
{
lock (locker)
{
counter++;
}
}
public void Assert(int input)
{
if (input != counter)
{
throw new InvalidOperationException($"Input {input}, counter {counter}");
}
}
}
class SerialQueueExample
{
readonly SerialQueue queue = new SerialQueue();
private int counter = 0;
public void SomeMethod()
{
queue.DispatchAsync(() => {
counter++;
});
}
public void Assert(int input)
{
if (input != counter)
{
throw new InvalidOperationException($"Input {input}, counter {counter}");
}
}
}
}
@MonkAlex
Copy link
Author

MonkAlex commented Apr 1, 2024

Выше ошибка, вместо DispatchAsync нужно использовать DispatchSync
Тогда производительность на линейном чтении отвратительная:

Method Repeat Mean Error StdDev Median Completed Work Items Lock Contentions
Lock 10 172.3 ns 1.65 ns 1.55 ns 171.8 ns - -
QueueExample 10 70,694.3 ns 3,443.19 ns 10,152.32 ns 68,911.5 ns 9.9977 -
Lock 100 1,653.5 ns 27.56 ns 25.78 ns 1,650.7 ns - -
QueueExample 100 630,806.0 ns 18,771.76 ns 55,348.95 ns 627,627.9 ns 99.9912 -
Lock 1000 16,217.1 ns 129.39 ns 121.03 ns 16,173.7 ns - -
QueueExample 1000 6,623,032.2 ns 217,067.14 ns 640,027.37 ns 6,619,225.0 ns 999.8203 -
Lock 10000 160,593.7 ns 671.25 ns 595.05 ns 160,679.1 ns - -
QueueExample 10000 62,459,690.0 ns 2,151,567.18 ns 6,242,086.51 ns 59,985,133.3 ns 9997.6667 -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment