C#函数在预调用后的时间测量速度更快吗?

C# Functions faster in time measurement after pre-calling it?

我只是想找出为什么函数在测量时间之前被调用一次后似乎 运行 更快。

这是我的测量代码示例:

            float X = 0;
        FastMath.FireUp(); // Does nothing in this sample
        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < 5; i++)
        {
            X = FastMath.FastSin(i);
        }
        watch.Stop();
        Console.WriteLine("TIME : " + watch.Elapsed );

在这里你可以看到我调用的函数:

        public static float FastSin(float val)
    {
        int index = 360 - ((int)val % 360);
        if(index == 360)
        {
            return 0;
        }
        return -TRIGONOMETRIC_LOOKUPTABLE[index];
    }

事实是,我的测量显示以下输出:

TIME : 00:00:00.0001196

让我们用以下内容填充 "FireUp" 函数:

float x = FastSin(123);

现在测量时间明显减少:

00:00:00.0000015

但是,"FastCos",没有在FireUp函数中调用,仍然需要更长的时间。

还有两点我要提一下:

为什么会这样?

该方法是即时编译 (jit)。这就是为什么它在被调用后速度更快的原因。

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code.

在运行时 MSIL 代码(通过 JIT)编译为二进制平台相关代码。 CLR 编译刚刚使用的代码片段,然后它会在第一次调用之前编译 FastSin 方法。

The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run.

您可以阅读有关 MSIL and Compiling MSIL to Native Code 的更多信息。