Skip to content

Instantly share code, notes, and snippets.

@neon-sunset
Last active December 9, 2023 17:35
Show Gist options
  • Save neon-sunset/5d10006379242d0d225ededa531c56f6 to your computer and use it in GitHub Desktop.
Save neon-sunset/5d10006379242d0d225ededa531c56f6 to your computer and use it in GitHub Desktop.
Illustrating cache line sharing penalty
using System.Diagnostics;
// Change to 128 on ARM64 macOS
const int CACHELINE = 64;
const int iterations = 10_000_000;
var coreCount = Environment.ProcessorCount;
Console.WriteLine($"""
Time to increment an int {iterations} times on {coreCount} cores.
Cache line sharing coefficient is the count of cores that have to compete for the same cache line.
--------------------------------------------------------------------------------------------------
""");
var arrayLength = coreCount;
var maxPadding = CACHELINE * coreCount / sizeof(int);
while (arrayLength <= maxPadding)
{
var bytesPerInt = arrayLength / sizeof(int);
Console.WriteLine(
$"Padding: {bytesPerInt} bytes\n" +
$"Cache line sharing coefficient: {(float)CACHELINE / bytesPerInt}x");
var counters = new int[arrayLength];
var start = Stopwatch.GetTimestamp();
Parallel.For(0, coreCount, core =>
{
var stride = arrayLength / coreCount;
for (var i = 0; i < iterations; i++)
{
counters[stride * core]++;
}
});
Console.WriteLine(
$"Time: {Stopwatch.GetElapsedTime(start).TotalMilliseconds}ms\n");
arrayLength += coreCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment