Slow writing to an array in C ++

I'm just wondering if this behavior is expected in C ++. Below is the code below 0.001 ms:

for(int l=0;l<100000;l++){
        int total=0;
        for( int i = 0; i < num_elements; i++) 
        {
            total+=i;
        }
    }

However, if the results are written to an array, the execution time is increased to 15 ms:

int *values=(int*)malloc(sizeof(int)*100000);
        for(int l=0;l<100000;l++){
            int total=0;
            for( unsigned int i = 0; i < num_elements; i++) 
            {
                total+=i;
            }
            values[l]=total;
        }

I can understand that writing to an array takes time, but is proportional to time?

Greets everyone

+5
source share
4 answers

CPU. . , , , L1 , , L2 ( ). . , 15 /100.000 1,5 - 667 . .

+11

, .

- -op, .

+10

. 3 , GPR ( ), , , , , - L1, , .

100 . , 400 . - L1. - L2, , , L2. - , L1, L2 ( , L3), , , muuuuuch.

+3

, , , . malloc , , , . .

You can also measure the cost of a call mallocdepending on how you synchronized the cycle. In any case, performance will be very sensitive to compiler optimization options, streaming options, compiler versions, run-time versions, and more. You cannot safely assume that the cost is linear with the size of the distribution. The only thing you can do is measure it and figure out how best to optimize as soon as it turns out that this is a problem.

+1
source

All Articles