Skip to content

Instantly share code, notes, and snippets.

@defufna
Created June 6, 2023 17:46
Show Gist options
  • Save defufna/c0f59ff2b6d7eb1dcfb88cf0db947909 to your computer and use it in GitHub Desktop.
Save defufna/c0f59ff2b6d7eb1dcfb88cf0db947909 to your computer and use it in GitHub Desktop.
Cache line contention
using System.Diagnostics;
internal class Program
{
static long[] counters;
const int timeLimit = 20 * 1000;
static void Count(int index)
{
Stopwatch sw = Stopwatch.StartNew();
while(sw.ElapsedMilliseconds < timeLimit)
{
counters[index]++;
}
}
private static void Main(string[] args)
{
int stride = 1; // 128/sizeof(long);
Thread[] threads = new Thread[Environment.ProcessorCount];
counters = new long[threads.Length * stride];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = StartThread(i * stride);
}
Wait(threads);
Console.WriteLine(counters.Sum() / 1000000.0);
}
private static void Wait(Thread[] threads)
{
foreach (Thread t in threads)
{
t.Join();
}
}
private static Thread StartThread(int index)
{
Thread thread = new Thread(() => Count(index));
thread.Start();
return thread;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment