2

Following this question "What is “cache-friendly” code?" I've created dynamic 2d array to check how much time would it take to access elements column-wise and row-wise.

When I create an array in the following way:

const int len = 10000;
int **mass = new int*[len];
for (int i = 0; i < len; ++i)
{
    mass[i] = new int[len];
}

it takes 0.239 sec to traverse this array row-wise and 1.851 sec column-wise (in Release).

But when I create an array in this way:

auto mass = new int[len][len];

I get an opposite result: 0.204 sec to traverse this array row-wise and 0.088 sec column-wise.

My code:

const int len = 10000;
int **mass = new int*[len];
for (int i = 0; i < len; ++i)
{
    mass[i] = new int[len];
}

// auto mass = new int[len][len]; // C++11 style

begin = std::clock();
for (int i = 0; i < len; ++i)
{
    for (int j = 0; j < len; ++j)
    {
        mass[i][j] = i + j;
    }
}
end = std::clock();

std::cout << "[i][j] " << static_cast<float>(end - begin) / 1000 << std::endl;

begin = std::clock();
for (int i = 0; i < len; ++i)
{
    for (int j = 0; j < len; ++j)
    {
        mass[j][i] = i + j;
    }
}
end = std::clock();
std::cout << "[j][i] " << static_cast<float>(end - begin) / 1000 << std::endl;

Please, can you explain what is the difference between these ways to allocate memory for two-dimentional dynamic array? Why does it faster to traverse array row-wise in first way and column-wise in second way?

Community
  • 1
  • 1
Ann Orlova
  • 1,338
  • 15
  • 24
  • I can't see a difference at my VS2010 and also at http://rextester.com/WMN93569. here is gcc edition http://rextester.com/BAYM28948 – Jim Yang Apr 03 '14 at 05:38
  • 2
    I would suggest running the test multiple times with a larger number of datasets and analyzing the average times. Times in the area of a second can be heavily influenced by other processes running in background. – Tim Meyer Apr 03 '14 at 05:39
  • What compiler and platform? – ganz Apr 03 '14 at 05:40
  • To @Tim Meyer: when I changed the order of traversal (column-wise and then row-wise) I've got the same result for the first way of allocation; but for the second way I've got 0.086 sec for row-wise traversal and 0.175 sec for column wise traversal. – Ann Orlova Apr 03 '14 at 06:05
  • To @ganz: I use Microsoft Visual C++ 2013 on Windows 7(64bit) – Ann Orlova Apr 03 '14 at 06:06
  • 1
    mingw g++ gives the same result for both. You can always check the ordering of a 2d array by filling it up like so `*(&mass[0][0]+i) = i;` then accessing some elements (only the second case). – Cramer Apr 03 '14 at 06:32
  • @Ann Orlova I was speaking of setting len to e.g. 1000000 and running the test for both cases 5 times – Tim Meyer Apr 03 '14 at 09:58
  • @Tim Meyer: Yes, I've done so but results are the same (+- 10 ms) – Ann Orlova Apr 04 '14 at 08:10

0 Answers0