How to invalidate cache when benchmarking?
- by Michael Buen
I have this code, that when swapping the order of UsingAs and UsingCast, their performance also swaps.
using System;
using System.Diagnostics;
using System.Linq;
using System.IO;
class Test
{
const int Size = 30000000;
static void Main()
{
object[] values = new MemoryStream[Size];
UsingAs(values);
UsingCast(values);
Console.ReadLine();
}
static void UsingCast(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
if (o is MemoryStream)
{
var m = (MemoryStream)o;
sum += (int)m.Length;
}
}
sw.Stop();
Console.WriteLine("Cast: {0} : {1}", sum,
(long)sw.ElapsedMilliseconds);
}
static void UsingAs(object[] values)
{
Stopwatch sw = Stopwatch.StartNew();
int sum = 0;
foreach (object o in values)
{
if (o is MemoryStream)
{
var m = o as MemoryStream;
sum += (int)m.Length;
}
}
sw.Stop();
Console.WriteLine("As: {0} : {1}", sum,
(long)sw.ElapsedMilliseconds);
}
}
Outputs:
As: 0 : 322
Cast: 0 : 281
When doing this...
UsingCast(values);
UsingAs(values);
...Results to this:
Cast: 0 : 322
As: 0 : 281
When doing just this...
UsingAs(values);
...Results to this:
As: 0 : 322
When doing just this:
UsingCast(values);
...Results to this:
Cast: 0 : 322
Aside from running them independently, how to invalidate the cache so the second code being benchmarked won't receive the cached memory of first code?
Benchmarking aside, just loved the fact that modern processors do this caching magic :-)