分配函数值和不分配给变量之间的速度差异

Speed difference between assign function value and not assign to a variable

所以这对我来说真的是个谜。我正在测量我自己的正弦函数的时间并将其与标准 sin() 进行比较。虽然有一个奇怪的行为。当我单独使用这些功能时,例如:

sin(something);

我得到的平均时间是(在 10 轮中测量 1000000 次调用)3.1276 ms 对于标准正弦函数和 51.5589 ms我的实施。 但是当我使用这样的东西时:

float result = sin(something);

我的标准 sin() 突然 76.5621 毫秒,我的 49.3675 ​​毫秒。我知道将值分配给变量需要一些时间,但为什么它不也为我的正弦增加时间?它或多或少是相同的,而标准的则迅速增加。

编辑: 我的测量代码:

ofstream file("result.txt",ios::trunc);
file << "Measured " << repeat << " rounds with " << callNum << " calls in each \n";
for (int i=0;i<repeat;i++)
{
    auto start = chrono::steady_clock::now();

    //call the function here dattebayo!
    for (int o=0; o<callNum;o++)
    {
      double g = sin((double)o);
    }

    auto end = chrono::steady_clock::now();

    auto difTime = end-start;
    double timeD = chrono::duration <double,milli> (difTime).count();
    file << i << ": " << timeD << " ms\n";
    sum += timeD;
}

在任何现代编译器中,编译器都知道 sincosprintf("%s\n", str) 等函数,并且可以转换为更简单的形式 [constant if the value is常量,printf("%s\n", str);变成puts(str);]或者完全去掉[如果知道函数本身没有"side-effects",换句话说,它只是计算返回值,对其他方式的系统]。

即使对于标准函数,即使编译器处于低优化模式甚至没有优化模式,这种情况也经常发生。

您需要确保函数的结果真正用于在优化模式下调用它。在循环中将返回值相加...