user1701840
user1701840

Reputation: 1112

Why does stopwatch tick longer when it is running the first time

I run this code inside a while loop for like 10000 times, I noticed timeSpent is around 4 except for the first time, which is ~500, why?

Stopwatch s;
long price;
count = 10000;
while (count!=0)
{
   s = Stopwatch.StartNew();

   price = classA.Method(..some inputs...);  //this method do some iterations to return back a long given some inputs

   s.Stop();
   timeSpent = s.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
   s.Reset();
   /*write the price, timeSpent and inputs into a .txt file*/
   count--;
}

Upvotes: 0

Views: 559

Answers (1)

Paul Phillips
Paul Phillips

Reputation: 6259

The first time a method is called, it is compiled from IL to native code. Any subsequent calls re-use the generated native code. So, in general, you would expect the first time you call a method to take the longest.

It's difficult to prove this is the cause, unfortunately, but that might explain it. I've seen this same thing happen many times when benchmarking / profiling: the first call takes the longest. I've usually worked around this by just discarding the first run.

Of course, the method you're calling could have side-effects, acquire resources and cache them, or just anything that only happens once and only on the first call. These are just some of the reasons I say it's hard to be sure.

Upvotes: 2

Related Questions