2

When I did benchmark my code I noticed that the first run is too slow and the next runs are too fast. what is the reason?

for (int i = 0; i < 10; i++)
{
    var timer = new Stopwatch();
    timer.Start();
    var expression = new Expression('x');
    Console.WriteLine(timer.ElapsedTicks);
}

And the results

15096
6
0
1
1
1
1
1
0

Is there any way to always get the maximum speed even at first run?

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • What `Expression` class are you instantiating? The one in `System.Linq.Expressions` is abstract, and I can't find any other class with a constructor that takes a char parameter. – Jacob Bundgaard Apr 26 '15 at 15:10
  • oh. no that custom class named expression.i named it expression.@JacobBundgaard – M.kazem Akhgary Apr 26 '15 at 15:11

3 Answers3

4

You are measuring jitter overhead. Just In Time. It is mostly disk overhead in the case of Expression, its ngen-ed code needs to be loaded from the System.Core.ni.dll file into RAM. Or in other words, you are measuring the cost of a hard page fault. It will stay resident for a while, that's why it is fast the 2nd and subsequent times you invoke its constructor.

No, you always have to pay this cost.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2

I think this is because C# is a "Just In Time Compiled" language.

I expect that on the first iteration, the code is dynamically compiled into the machine specific code, and put in a cache. For the next iterations, the overhead of compiling the code does not exist anymore because the compiled code is taken out of the cache.

There can be other reasons that have to do with cache warming, but probably the first reason is the cause.

VAndrei
  • 5,420
  • 18
  • 43
-2

You should be reusing your timer and utilizing the Stop function in order to properly use a Timer.

i.e. Something similar to this:

var timer = new Stopwatch();        
for (int i = 0; i < 10; i++)
{
    timer.Start();
    var expression = new Expression('x');
    timer.Stop();
    Console.WriteLine(timer.ElapsedTicks);
    timer.Reset();
 }
Austinh100
  • 598
  • 3
  • 13