在C++中将 double 数添加到很大的 double 动态 vector 时,我遇到了一些未知的减速问题。
如下所示,出现速度下降的原因似乎是由于添加了一个倍数,该倍数是根据cos和sin函数的长期求和得出的。
当仅将A_temp1添加到动态 vector 时,不会降低速度:
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添加到 vector 中时,速度会明显下降:
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都是 double 值,也不会导致速度降低。
A_temp2特别来自一个函数,该函数涉及cos和sin函数的总和。可能是由于该号码的存储方式所致,但我无法弄清楚原因。
如果有人在这种情况下为什么会出现减速以及如何避免这种情况,我将不胜感激。
谢谢!
最佳答案
如果您根本不使用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.
关于c++ - 在C++中向动态 vector 添加 double 时的神秘减速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625839/