Hier ist einfacher C++ - Code, der das Iterieren von 2D-Array-Zeilenmajor mit Spaltenmajor vergleicht. Warum wird die iterierende 2D-Array-Zeile schneller als die Spaltenhauptreihe?
#include <iostream>
#include <ctime>
using namespace std;
const int d = 10000;
int** A = new int* [d];
int main(int argc, const char * argv[]) {
for(int i = 0; i < d; ++i)
A[i] = new int [d];
clock_t ColMajor = clock();
for(int b = 0; b < d; ++b)
for(int a = 0; a < d; ++a)
A[a][b]++;
double col = static_cast<double>(clock() - ColMajor)/CLOCKS_PER_SEC;
clock_t RowMajor = clock();
for(int a = 0; a < d; ++a)
for(int b = 0; b < d; ++b)
A[a][b]++;
double row = static_cast<double>(clock() - RowMajor)/CLOCKS_PER_SEC;
cout << "Row Major : " << row;
cout << "\nColumn Major : " << col;
return 0;
}
Ergebnis für verschiedene Werte von d:
d = 10^3:
= 0Row-Dur: 0,002431
Spaltenhaupt: 0,017186
d 10^4:
Zeilenhaupt: 0,237995
Spaltenhaupt: 2,04471
d = 10^5
Zeilenhaupt: 53.9561
Spalte Haupt: 444.339
Jetzt ist die Frage, warum Zeile Haupt schneller als Spalte Haupt ist?
, weil in C-Arrays sind ** Zeile Major ** und wegen ** räumliche Lokalität ** des ** Cache **. – bolov
Mögliches Duplikat von [Warum spielt Cache-Lokalität für die Array-Leistung eine Rolle?] (Http://stackoverflow.com/questions/12065774/why-does-cache-locity-matter-for-array-performance) – bolov
Diesmal geht es nicht darum Verzweigungsvorhersage :). In beiden Versionen haben Sie die gleiche Anzahl an Vergleichen, und beide Male ist das 'true' /' false' Muster das gleiche (dh viele 'wahre' Bedingungen und dann ein' false' Muster - wenn der Index das Ende erreicht) – bolov