Suppose I have two methods, Foo
and Bar
, that do roughly the same thing, and I want to measure which one is faster. Also, single execution of both Foo
and Bar
is too fast to measure reliably.
Normally, I'd simply run them both a huge number of times like this:
var sw=new Stopwatch();
sw.Start();
for(int ii=0;ii<HugeNumber;++ii)
Foo();
sw.Stop();
Console.WriteLine("Foo: "+sw.ElapsedMilliseconds);
// and the same code for Bar
But in this way, every run of Foo
after the first will probably be working with processor cache, not actual memory. Which is probably way faster than in real application. What can I do to ensure that my method is run cold every time?
Clarification
By "roughly the same thing" I mean the both methods are used in the same way, but actual algorithm may differ significantly. For example, Foo
might be doing some tricky math, while Bar
skips it by using more memory.
And yes, I understand that methods running in cold will not have much effect on overall performance. I'm still interested which one is faster.