这里有些免费的函数,它们在第一种情况下没有向量化循环,但在其他情况下则是向量化的。为什么会这样呢?
#include <vector>
typedef std::vector<double> Vec;
void update(Vec& a, const Vec& b, double gamma) {
const size_t K = a.size();
for (size_t i = 0; i < K; ++i) { // not vectorized
a[i] = b[i] * gamma - a[i];
}
}
void update2(Vec& a, const Vec& b, double gamma) {
for (size_t i = 0; i < a.size(); ++i) { // vectorized
a[i] = b[i] * gamma - a[i];
}
}
void update3(Vec& a, size_t K, const Vec& b, double gamma) {
for (size_t i = 0; i < K; ++i) { // vectorized
a[i] = b[i] * gamma - a[i];
}
}
int main(int argc, const char* argv[]) {
Vec a(argc), b;
update(a, b, 0.5);
update2(a, b, 0.5);
update3(a, a.size(), b, 0.5);
return 0;
}
编译器(VS2013)的相关提示信息:
1> c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(7) : info C5002: loop not vectorized due to reason '1200'
1> c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(13) : info C5001: loop vectorized
1> c:\home\dima\trws\trw_s-v1.3\trws\test\vector.cpp(19) : info C5001: loop vectorized
来自@tony的评论
原因1200:"循环包含循环传递的数据依赖关系,防止向量化。循环的不同迭代互相干扰,使得向量化循环会产生错误的答案,并且自动向量化器无法证明不存在这样的数据依赖关系。" 来源
a
和b
不是别名,要么&a[0] < &b[0]
。 - Mysticial