[英]Fastest way to add consecutive groups of vector elements in C++
我有120个元素的向量。 我需要每组20个值的总和(总共6套)。 我目前正在使用两个嵌套的for循环,如下所示:
for (int j = 0; j < 120; j+=20)
for (int i = j; i < (j +20); i++)
sum += vector[i]
code where I use the sum
仅使用STL存在哪些更好(更快)的方法?
在这里使用标准库可能不会有多大(如果有的话)差异,但可能会使代码更加整洁:
auto const stride = 20;
for (auto b = vec.begin(); b < vec.end(); b+=stride) {
auto sum = std::accumulate(b, b+stride, 0);
use(sum);
}
首先,您可以保存6个添加项:
for (int j = 0; j < 120; j += 20) {
auto sum = vector[j];
for (int i = j + 1; i < j + 20; i++)
sum += vector[i];
// code which uses the sum
}
其次,您可以使用std :: accumulate,希望您的实现可以以某种方式对其进行优化:
auto it = vector.cbegin();
for (int j = 0; j < 120; j += 20) {
auto itNext = it + 20;
auto sum = std::accumulate(it + 1, itNext, *it);
// code which uses the sum
it = itNext;
}
但是请注意,除非vector
位于高速缓存存储器中,否则这些或其他任何改进措施最多都是微不足道的。 在这种情况下,从RAM读取向量所花费的时间要远远长于算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.