SA-MP Forums Archive
while() is faster than for() ??? - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: while() is faster than for() ??? (/showthread.php?tid=562225)



while() is faster than for() ??? - sw3das - 07.02.2015

Hey everybody.
Just wanted to make sure that my tests are correct. When I'm running this code:
Код:
#include <a_samp>

main(){}

public OnGameModeInit( )
{
	new time, i = 0,
	tMax = 10000000;
	
	time = GetTickCount( );
	
	for( i=0; i < tMax; i++ ){}
	
	printf( "for loop = %i ms", GetTickCount( ) - time );
	
	time = 0, i = 0;
	
	time = GetTickCount( );
	while( i < tMax ){i++;}
	printf( "while loop = %i ms", GetTickCount( ) - time );
}
I get the following results:
Код:
[20:31:50] for loop = 648 ms
[20:31:50] while loop = 355 ms
Am I doing something wrong or while() loop is actually 2x faster ?? :O


Re: while() is faster than for() ??? - MicroD - 07.02.2015

Dйjа vu. Do not worry about loops and how they're done, just use them efficiently!


Re: while() is faster than for() ??? - Misiur - 07.02.2015

Interesting, though not reliable results:
Quote:

[19:50:56] for loop = 677 ms
[19:50:57] while loop = 1256 ms

Pcode for "for" loop:
pawn Код:
jump 2
l.0     ; a0
    ; line c
    break   ; a0
    load.s.pri fffffff8
    inc.s fffffff8
    ;$exp
l.2
    load.s.pri fffffff8
    push.pri
    load.s.pri fffffff4
    pop.alt
    xchg
    sless
    jzer 1
    ;$exp
    jump 0
l.1     ; e4
Pcode for "while" loop:
pawn Код:
break   ; 190
l.3     ; 194
    ; line 13
    break   ; 194
    load.s.pri fffffff8
    push.pri
    load.s.pri fffffff4
    pop.alt
    xchg
    sless
    jzer 4
    ;$exp
    ; line 13
    break   ; 1c0
    load.s.pri fffffff8
    inc.s fffffff8
    ;$exp
    jump 3
l.4     ; 1dc
Also 10000000 is quite a big number, the difference in real world is negligible, you won't have a 10^7 iterations ever.


Re: while() is faster than for() ??? - iZN - 07.02.2015

I can assure you that the speed comparison won't matter unless you're going to perform many iterations, by many I mean in more than thousands.


Re: while() is faster than for() ??? - BlackBank - 08.02.2015

I've run exactly your code, and this are the results i get:
Код:
[02:47:28] for loop = 511 ms
[02:47:29] while loop = 874 ms
So a for loop is still faster for me... :P