-
-
Save MonkAlex/f9df69aa26ae06896aa374563896dba0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using Threading.Tasks; | |
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(); | |
var tasks = new Task[Repeat]; | |
for (int i = 0; i < Repeat; i++) | |
{ | |
tasks[i] = a.SomeMethod(); | |
} | |
Task.WaitAll(tasks); | |
a.Assert(Repeat); | |
} | |
[Benchmark] | |
public void QueueExample() | |
{ | |
var a = new SerialQueueExample(); | |
var tasks = new Task[Repeat]; | |
for (int i = 0; i < Repeat; i++) | |
{ | |
tasks[i] = a.SomeMethod(); | |
} | |
Task.WaitAll(tasks); | |
a.Assert(Repeat); | |
} | |
} | |
class Lock | |
{ | |
readonly object locker = new object(); | |
private int counter = 0; | |
public async Task 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 async Task SomeMethod() | |
{ | |
await queue.Enqueue(() => { | |
counter++; | |
}); | |
} | |
public void Assert(int input) | |
{ | |
if (input != counter) | |
{ | |
throw new InvalidOperationException($"Input {input}, counter {counter}"); | |
} | |
} | |
} | |
} |
Author
MonkAlex
commented
Apr 1, 2024
Method | Repeat | Mean | Error | StdDev | Completed Work Items | Lock Contentions |
---|---|---|---|---|---|---|
Lock | 10 | 286.3 ns | 4.70 ns | 4.39 ns | - | - |
QueueExample | 10 | 3,286.7 ns | 11.63 ns | 10.88 ns | 1.0432 | 0.0000 |
Lock | 100 | 2,643.7 ns | 9.04 ns | 7.55 ns | - | - |
QueueExample | 100 | 18,457.2 ns | 126.04 ns | 117.89 ns | 1.1713 | - |
Lock | 1000 | 26,740.9 ns | 404.33 ns | 378.21 ns | - | - |
QueueExample | 1000 | 442,683.7 ns | 5,938.82 ns | 5,555.17 ns | 1.0229 | - |
Lock | 10000 | 266,280.9 ns | 2,956.81 ns | 2,765.81 ns | - | - |
QueueExample | 10000 | 2,650,321.9 ns | 55,982.63 ns | 165,066.06 ns | 2.6875 | - |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment