C# 为什么秒表第一次运行时滴答声更长

C# 为什么秒表第一次运行时滴答声更长,c#,.net,performance,stopwatch,C#,.net,Performance,Stopwatch,我在while循环中运行这段代码大约10000次,我注意到timespunt大约是4,除了第一次是~500,为什么 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 giv

我在while循环中运行这段代码大约10000次,我注意到timespunt大约是4,除了第一次是~500,为什么

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--;
}

第一次调用方法时,将其从IL编译为本机代码。任何后续调用都将重新使用生成的本机代码。因此,一般来说,第一次调用方法的时间最长

不幸的是,很难证明这是原因,但这也许可以解释它。在进行基准测试/评测时,我多次看到同样的情况:第一次调用花费的时间最长。我通常通过放弃第一次跑步来解决这个问题


当然,您正在调用的方法可能会产生副作用,获取资源并缓存它们,或者只是在第一次调用时只发生一次的任何事情。这些只是我说很难确定的一些原因。

什么是/*函数调用*/?其中一个可能正在初始化某些内容。你不应该在循环外启动秒表吗?即使它正在初始化某些内容,当它再次被调用时,它将再次初始化,不是吗?我怀疑您忽略的函数调用是第一次被命中,并且您看到了使用JIT语言的成本。使用Stopwatch.elapsedmillesons比自己使用tick进行计算要容易得多,或者其中一个类具有静态构造函数。