【问题标题】:Mysterious slowdown when adding doubles to dynamic vector in C++在 C++ 中向动态向量添加双精度时出现神秘的减速
【发布时间】:2020-05-06 01:32:25
【问题描述】:

在 C++ 中将双精度添加到非常大的双精度动态向量时,我遇到了一些未知的减速。

如下所示,减速似乎是由于添加了一个双精度数,该双精度数是根据 cos 和 sin 函数的冗长总和计算得出的。

当只有A_temp1加入动态向量时,没有减速:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp1 = pi;
       A_temp2 = [long-winded sum of sin and cos operations]; 
    // no slowdown if only A_temp1 is  added
        A_dyn_vec[i] = A_temp1; 
    }

但是,当将 A_temp2 添加到向量中时,速度会明显下降:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp1 = pi;
       A_temp2 = [long-winded sum of sin and cos operations]; 
    // significant slowdown 
        A_dyn_vec[i] = A_temp1 + A_temp2; 
    }

此外,当两者合并为一个 A_temp 值时,会出现同样的显着减速:

    for(int i=0;i<=imax;i++){
    // neither of these cause slowdown on their own
       A_temp = pi + [long-winded sum of sin and cos operations]; 
    // significant slowdown 
        A_dyn_vec[i] = A_temp;
    }

总而言之,由于某种原因,添加 A_temp1 不会导致减速,但 A_temp2 会,即使它们都是双精度数。

A_temp2 专门来自一个涉及 cos 和 sin 函数的冗长总和的函数。也许这个数字存储方式的性质导致了这个问题,但我无法弄清楚究竟是什么原因。

如果有人对为什么在这种情况下会出现减速以及如何避免这种情况有任何意见,我将不胜感激。

谢谢!

【问题讨论】:

  • Mahmood 的回答可能是正确的,但要获得具体的答案,您需要提供一个 minimal reproducible example,并附上编译时使用的优​​化参数。
  • 很遗憾,我无法分享完整的代码。但是,我认为他的答案是正确的。我没有考虑过优化例程。
  • 我们不想要完整的代码。正确构造的minimal reproducible example 将表现出您希望解释的行为,而不会做任何其他事情。因此,与完整代码相比,它几乎无法识别。

标签: c++ vector dynamic addition slowdown


【解决方案1】:

如果你根本不使用A_temp2,我相信这是一个编译器优化,它甚至没有计算数字,因为你没有使用它。当您开始在第二个代码中使用它时。它不能忽略导致减速的计算。

编辑:我认为在您的情况下帮助执行时间的唯一方法是使罪和余弦的总和更好。基本上只是减少你做的函数调用的数量。例如将sin(i)^2 + cos(i)^2 写为1。这将减少函数调用的数量。或执行以下操作。

temp1 = sin(i);
temp2 = cos(i);
do the sum operation with temp1 and temp2 instead of calling the sin and cos functions again and again.

【讨论】:

  • 这听起来像是最有可能发生的事情 - 非常感谢您的反馈。
  • 检查我的编辑。它可能会帮助你。也请将此线程标记为已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-20
  • 2016-12-19
  • 2013-05-15
  • 2021-05-14
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多