Skip to content

Instantly share code, notes, and snippets.

@badamczewski
Created February 19, 2015 05:49
Show Gist options
  • Save badamczewski/6a224ede862f083dbafa to your computer and use it in GitHub Desktop.
Save badamczewski/6a224ede862f083dbafa to your computer and use it in GitHub Desktop.
Misaligment Test .NET
class Program
{
int MAX_NUM_LINES = 1000;
int ALLOC_SIZE = 0;
int LINE_SIZE = 64;
int PG_SIZE = 4096;
int WORD_SIZE = 8;
public Program()
{
ALLOC_SIZE = (2 * MAX_NUM_LINES * PG_SIZE);
}
public long access_mem(int align, int n, int runs, int pointer_chase)
{
int[] a = new int[ALLOC_SIZE];
int sum = 0;
int i, j;
// Fill up array with some nonsense
for (i = 0; i < n * PG_SIZE; i++)
{
a[i] = i % 17;
}
int offset = 0;
for (i = 0; i < n * PG_SIZE; i += (PG_SIZE + align) / WORD_SIZE)
{
offset += (PG_SIZE + align) / WORD_SIZE;
a[i] = offset;
}
a[n * PG_SIZE / WORD_SIZE] = 0;
long totalMs = 0;
Stopwatch w = new Stopwatch();
for (i = 0; i < runs; i++)
{
offset = 0;
//RDTSC_START(tsc_before);
w.Start();
for (j = 0; j < n; j++)
{
sum += a[offset];
if (pointer_chase == 1)
{
offset = a[offset];
}
else
{
offset += PG_SIZE + align;
}
}
}
w.Stop();
//RDTSC_STOP(tsc_after);
//tsc = tsc_after - tsc_before;
//min_tsc = min_tsc < tsc ? min_tsc : tsc;
totalMs += w.ElapsedMilliseconds;
return totalMs;
}
public void test_and_print(int n, int pointer_chase)
{
double diff;
long aligned_time, unaligned_time;
int runs = 100000;
aligned_time = access_mem(0, n, runs, pointer_chase);
unaligned_time = access_mem(16, n, runs, pointer_chase);
diff = (double)aligned_time / (double)unaligned_time;
Console.WriteLine("----------{0} accesses--------\n", n);
Console.WriteLine("Page-aligned time: {0}", aligned_time);
Console.WriteLine("Page-unaligned (+64) time: {0}", unaligned_time);
Console.WriteLine("Difference: {0}\n", diff);
}
static void Main(string[] args)
{
Program p = new Program();
p.test_and_print(512, 0);
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment