Many nested for loops versus single loop

I did a little speed testing in C ++ (MSVS) and got a weird result. I tested the speed of using one for a loop against multiple nested loops. Here is the code:

double testX = 0;
// Single loop executes in roughly 0.04 seconds
for( int i = 0; i < 27000000; i++ ){
    testX += 1;
}

// Nested loop executes in roughly 0.03 seconds
for( int x = 0; x < 300; x++ ){
    for( int y = 0; y < 300; y++ ){
        for( int z = 0; z < 300; z++ ){
            testX += 1;
        }
    }
}

As you can see, the speed difference is pretty obvious. I have run this many times and this is the average time I see (they are synchronized using glfwGetTime ()).

So my question is: why? Is my testing method inadequate? Am I using too few loops? I tried to find google, and the only similar question I could find related its problem with caching coherency, but since they are empty for loops, I did not think that this would really have an effect.

Any help is determined :)

:. , , , ... , () . . , , .

, ( /, ).

+5
3

"" , testX - . testX, :

  • single for loop: 1.218 ms
  • nested for loop: 1.218 ms

, , . :

for( int i = 0; i < 27000000; i++ ){
    testX += i;
}

for( int x = 0; x < 300; x++ ){
    testX += x;
    for( int y = 0; y < 300; y++ ){
        testX += y;
        for( int z = 0; z < 300; z++ ){
            testX += z;
        }
    }
}

,

  • single for loop: 1.224 ms
  • nested for loop: 1.226 ms

30 000 .

: testX += x; 1 90000, testX += x; 1 300. , .

, , , true.

: , , 40 , . , . , glfwGetTime() , . ?

: , :

int lmt = rand() % 1 + 300;      // random value 300 or 301 
int big_lmt = lmt * lmt * lmt;   // random value 27000000 or 27270901

for( int i = 0; i < big_lmt; i++ ){
    testX += i;
}

for( int x = 0; x < lmt; x++ ){
    testX += x;
    for( int y = 0; y < lmt; y++ ){
        testX += y;
        for( int z = 0; z < lmt; z++ ){
            testX += z;
        }
    }
}

.

( lmt = 300 ):

  • single for loop: 1.213 ms
  • nested for loop: 1.216 ms

:

  • , .
+7

for (x, y, z) for, ( ) for . ​​ , , x, y, z stdin ..

, - testX (, stdout), ( ) , .. .

, , , , - .

+1

, , .

0

All Articles