首页 > 解决方案 > 在 C++ 中向动态向量添加双精度时出现神秘的减速

问题描述

在 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 函数的冗长总和的函数。也许这个数字存储方式的性质导致了这个问题,但我无法弄清楚究竟是什么原因。

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

谢谢!

标签: c++vectordynamicadditionslowdown

解决方案


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

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

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.

推荐阅读