Last active
February 27, 2024 17:35
-
-
Save LuizZak/9cd03f8b090ffc56af15 to your computer and use it in GitHub Desktop.
C# rolled vs unrolled loop
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 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