some crazy stuff about loop optimization
#1

6 loops
all make the same thing
all make 100milion iterations
but they spend VERY different times

PHP код:
    new GetTickCount();
    new 
0;
    
    
    
GetTickCount();
    while( 
1000000000 )
        if(
n++ == 100000000)
            break;
    
printf("tempo1 = %d",GetTickCount() - a);
    
0;
    
GetTickCount();
    while( 
200000000 )
        if(
n++ == 100000000)
            break;
    
printf("tempo2 = %d",GetTickCount() - a);
    
    
0;
    
GetTickCount();
    while( 
100000001 )
        if(
n++ == 100000000)
            break;
    
printf("tempo3 = %d",GetTickCount() - a);
    
    
0;
    
GetTickCount();
    while( 
)
        if(
n++ == 100000000)
            break;
    
printf("tempo4 = %d",GetTickCount() - a);
    
    
0;
    
GetTickCount();
    for(new 
0100000000t++)
        if(
n++ == 100000000)
            break;
    
printf("tempo5 = %d",GetTickCount() - a);
    
    
0;
    
GetTickCount();
    for(new 
010000002t++)
        if(
n++ == 100000000)
            break;
    
printf("tempo6 = %d",GetTickCount() - a); 
result:

Quote:

[23:41:30] tempo1 = 3705
[23:41:33] tempo2 = 3745
[23:41:37] tempo3 = 3733
[23:41:39] tempo4 = 1625
[23:41:41] tempo5 = 2698
[23:41:42] tempo6 = 268

now I ask:
why?
Reply
#2

Код:
[23:41:42] tempo6 = 268
is because the loop is stopping @ 10,000,000, all others are stopping @ 100,000,000. so the real value is more like 2680.

Код:
[23:41:39] tempo4 = 1625
is faster due to a missing insruction (math operator) using the "while( 1 < 2 )". the constant expressions are being precompiled, since the 1 and 2 are constants.
Reply
#3

I suppose number 4 is fastest because it uses constant values in the expression rather than variables. 1 will always be less than 2, so it wont have to check the value each iteration. (i guess)

EDIT: Didn't know this was already mentioned above.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)