Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在预调用C#函数后,它的时间测量速度更快?_C#_Function_Call_Stopwatch_Measurement - Fatal编程技术网

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

在预调用C#函数后,它的时间测量速度更快?,c#,function,call,stopwatch,measurement,C#,Function,Call,Stopwatch,Measurement,我只是想找出为什么函数在测量时间之前被调用一次后运行得更快 以下是我的测量代码示例: float X = 0; FastMath.FireUp(); // Does nothing in this sample Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 5; i++) {

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

以下是我的测量代码示例:

            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 );
所以问题是,我的测量结果显示如下输出:

时间:00:00:00.0001196

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

float x = FastSin(123);
现在测量的时间显著减少:

00:00:00.0000015

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

我还应该提到另外两点:

  • 如果我不调用“FireUp”功能,时间会再次增加: 时间:00:00:00.0002796

  • 如果我用以下内容填充“FireUp”函数:

    float x = FastSin(123);
    
    浮点数x=FastSin(123); x=FastCos(123)

    在将来的测量中,这两种功能都可以正常运行。 现在每个函数需要时间:00:00:00.0000019


为什么会发生这种情况?

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

编译为托管代码时,编译器会翻译源代码 将代码转换为Microsoft中间语言(MSIL),这是一种 与CPU无关的一组指令,可以有效地进行转换 转换为本机代码

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

运行时提供另一种编译模式,称为安装时间 代码生成。安装时代码生成模式转换MSIL 与常规JIT编译器一样,转换为本机代码,但它会转换 一次存储更大的代码单元,为 在随后加载并运行程序集时使用


您可以阅读有关和的更多信息。

JIT编译,您知道如何在visual studio 2015中禁用此类编译吗?我试图禁用JIT调试选项,但结果仍然相同。JIT编译器是clr的一部分。您可以使用ngen进行预编译。@Zerrox96通常的做法是首先为性能测试预热方法,甚至为大型框架初始化基础结构预热服务。