根据我在vs2013的测试,发现sum函数要比sum2快几十倍的速度,这完全得益于我们按照行来访问,这天然的符合vector的存储方式,另外在release情况下编译器会优化掉a[i][j],它会找一个临时变量 x = a[i],这样就不需要每次都去寻找a[i]了。
data_type sum(vector<vector<data_type>>& a,int k ){
auto M = a.size(), N = a[0].size();
data_type res = 0;
for (size_t i = 0; i != M; ++i)
{
for (size_t j = 0; j != N; ++j)
res +=a[i][j];
}
return res+k;
}
data_type sum2(vector<vector<data_type>>& a,int k){
auto M = a.size(), N = a[0].size();
data_type res = 0;
for (size_t j = 0; j != N; ++j)
{
for (size_t i = 0; i != M; ++i)
res += a[i][j];
}
return res+k;
}
再看一个关于空间局部性的例子:
struct point {
int vec[3];
int acc[3];
};
using p_array = vector<point>;
void clear(p_array& p ){
int n = p.size();
for (int i = 0; i != n; ++i)
{
auto& p1 = p[i];//编译器没有对这里进行优化for (int j = 0; j != 3; ++j)
p1.vec[j] = 0;
for (