Skip to content

Instantly share code, notes, and snippets.

@LuizZak
Last active February 27, 2024 17:35
Show Gist options
  • Save LuizZak/9cd03f8b090ffc56af15 to your computer and use it in GitHub Desktop.
Save LuizZak/9cd03f8b090ffc56af15 to your computer and use it in GitHub Desktop.
C# rolled vs unrolled loop
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace Test
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
RolledLoop();
UnrolledLoop();
}
public unsafe static void RolledLoop()
{
const int len = 256 * 256;
int* data = stackalloc int[len];
int* ptr = data;
int count = len;
var sw = Stopwatch.StartNew();
while (count-- > 0)
{
*(ptr++) = 0;
}
Debug.WriteLine(string.Format("65536 rolled loop: {0}ms", (sw.ElapsedTicks / (double)Stopwatch.Frequency)));
}
public unsafe static void UnrolledLoop()
{
const int len = 256 * 256;
int* data = stackalloc int[len];
int* ptr = data;
int count = len;
int rem = count % 8;
count /= 8;
var sw = Stopwatch.StartNew();
while (count-- > 0)
{
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
*(ptr++) = 0;
}
while (rem-- > 0)
{
*(ptr++) = 0;
}
Debug.WriteLine(string.Format("65536 unrolled loop: {0}ms", (sw.ElapsedTicks / (double)Stopwatch.Frequency)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment