Skip to content

Instantly share code, notes, and snippets.

@rchoffardet
Last active January 18, 2024 22:40
Show Gist options
  • Save rchoffardet/228f4bf1892e403c65487fcfe46afe35 to your computer and use it in GitHub Desktop.
Save rchoffardet/228f4bf1892e403c65487fcfe46afe35 to your computer and use it in GitHub Desktop.
Thread contention benchmark for exceptions
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Rchoffardet.Benchmarks.ExceptionPerformance;
var iterationCount = 10_000;
var method = 1;
var totalTimeNs = 0L;
var threadCounts = Enumerable.Range(1, 32);
foreach(var threadCount in threadCounts)
{
ExecuteConcurrently(() =>
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterationCount; i++)
{
try
{
_ = method switch
{
1 => ThrowIn1Call(),
2 => ReturnIn1Call(),
_ => throw new NotImplementedException()
};
}
catch(InvalidOperationException) {}
}
sw.Stop();
Interlocked.Add(ref totalTimeNs, (long)sw.Elapsed.TotalNanoseconds);
}, threadCount);
Console.WriteLine($"{1d * totalTimeNs / iterationCount / threadCount}");
}
static void ExecuteConcurrently(Action action, int parallelism)
{
var threads = new Thread[parallelism];
for (int i = 0; i < parallelism; i++)
{
threads[i] = new Thread(_ => action());
threads[i].Start();
}
for (int i = 0; i < parallelism; i++)
{
threads[i].Join();
}
}
[MethodImpl(MethodImplOptions.NoInlining)] static string ThrowIn1Call() => Throw();
[MethodImpl(MethodImplOptions.NoInlining)] static string Throw() => throw new InvalidOperationException("Something wrong append.");
[MethodImpl(MethodImplOptions.NoInlining)] static string ReturnIn1Call() => Return();
[MethodImpl(MethodImplOptions.NoInlining)] static string Return() => "Something wrong append.";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment