循环两次比在C++中循环一次快?

Sim*_*mon 1 c++ performance loops

这是我做的一个小测试,结果让我感到惊讶:做两次相同的循环大约是循环一次的两倍.我猜它是因为内存访问?

float* A = new float[1000000];
float* B = new float[1000000];
int h,w;
h = w = 1000;
CString txt;
double time1, time2;

time1 = Timer::instance()->getTime();
for(int j = 0; j < h; j++){
    for(int i = 0; i < w; i++){
        A[i+j*w] = 1;
        B[i+j*w] = 1;
    }
}
time2 = Timer::instance()->getTime();
txt.Format(_T("Both in same loop = %f"),time2-time1);
AfxMessageBox(txt);

time1 = Timer::instance()->getTime();
for(int j = 0; j < h; j++){
    for(int i = 0; i < w; i++){
        A[i+j*w] = 1;
    }
}
for(int j = 0; j < h; j++){
    for(int i = 0; i < w; i++){
        B[i+j*w] = 1;
    }
}
time2 = Timer::instance()->getTime();
txt.Format(_T("Different loops = %f"),time2-time1);
AfxMessageBox(txt);
Run Code Online (Sandbox Code Playgroud)

Chr*_*rle 8

它可能是CPU缓存,但更可能是并发内存访问.当您访问时array1[x],然后在此之后array2[x],这些是内存中两个非常不同的位置,并且很难进行优化.然而array[0],array[1],array[2]等都是在连续的内存和更高效的访问.英特尔似乎同意.