This may be a repeated question. Therefore, please feel free to mark this if you wish. In C ++, I found out that array sizes are stored sequentially in memory. How are 3D arrays stored in C? , so I did a little experiment to assign natural numbers to a matrix size of 1600000000x1 and 1x1600000000 (please change the matsize in the code to a lower value depending on your memory). The code below assigns natural numbers from 1 to 1,600,000,000 to the matrix a (whose dimensions are 1x1600000000) and calculates the sum of the cubes of all elements. The opposite case is simply to resize the matrix, which I do by changing xdim to matsize and ydim to 1, and recompiling the code and running it again. Matrix [xdim][ydim]
#include <iostream>
My results for two cases:
Case 1: xdim = 1 and ydim = 1600000000
highlighted. the time spent on isolation was 4.5e-05 seconds. the calculation began, the last number is 1.6e + 09. the sum is 1.6384e + 36 the calculation is done. the time taken to calculate was 14.7475 seconds redistributed. the time spent on release was 0.875754 seconds; the total time is 15.6233 or 15.6233 seconds
Case 2: xdim = 1600000000 and ydim = 1
highlighted. time spent on allocation amounted to 56.1583 seconds. the calculation began, the last number is 1.6e + 09. the sum is 1.6384e + 36 the calculation is done. time spent on the calculation was 50.7347 seconds redistributed. the time spent on release was 270.038 seconds; the total time is 320.773 or 376.931 seconds
The sum of the withdrawal is the same in both cases. I can understand that the time taken to allocate and free memory is different in both cases, but why is the calculation time so different if the memory allocation is continuous? What is wrong with this code?
If that matters, I use g ++ in Mountain Lion and compile using the quad-core processor g ++ -std = C ++ 11, i7, 16 GB of RAM.
source share