Some benchmarking about swapping two variables

Code snippets illustrating how LBB can be used
Optimax
Posts: 3
Joined: Fri Jun 08, 2018 3:38 pm

Some benchmarking about swapping two variables

Post by Optimax »

As I am not an api-coder nor a C nor ASM fanatic, I post this small code only for the fun and for basic-hobbyists's entertainment.
I've read the arithmetic method somewhere, I can't remember where.
Every better (basic) method of swapping is welcome, don't hesitate to post it, I'll be happy to add it to my small collection.

Code: Select all

'SWAP.BAS       LBB 17-01-2018
'========

x = 2
y = 3
PRINT "let x = "; x
PRINT "let y = "; y
PRINT

'--- arithmetic method

PRINT "--- Swapping 10001 times x and y by an arithmetic method"
PRINT
t1 = TIME$("ms")
FOR n = 1 TO 10001   'must be ODD !
    x = x + y
    y = x - y    ' ' '  i.e.  x + y - y = x
    x = x - y    ' ' '  i.e.  x - x + y = y
NEXT n
t2 = TIME$("ms")
PRINT "time = "; t2 - t1; " msec"
PRINT "now x = "; x
PRINT "now y = "; y
PRINT

'--- with an intermediate variable< tmp>

PRINT "--- Swapping 10001 times x and y with a temporary variable"
PRINT
t1 = TIME$("ms")
FOR n = 1 TO 10001
    tmp = x
    x = y
    y = tmp
NEXT n
t2 = TIME$("ms")
PRINT "time = "; t2 - t1; " msec"
PRINT "now x = "; x
PRINT "now y = "; y
PRINT

'--- using the extra-keyword  < ! SWAP >

PRINT "--- Swapping 10001 times x and y with the extra-keyword < !SWAP >"
PRINT
t1 = TIME$("ms")
FOR n = 1 TO 10001
    ! SWAP x, y
NEXT n
t2 = TIME$("ms")

PRINT "time = "; t2 - t1; " msec"
PRINT "now x = "; x
PRINT "now y = "; y
PRINT

'--- Terminate

PRINT "ENTER/RETURN to terminate..."; 
INPUT enter$
!QUIT
END

tsh73
Posts: 44
Joined: Fri Apr 06, 2018 7:58 pm

Re: Some benchmarking about swapping two variables

Post by tsh73 »

>>'must be ODD !
LOL
;)

Thanks.
Optimax
Posts: 3
Joined: Fri Jun 08, 2018 3:38 pm

Re: Some benchmarking about swapping two variables

Post by Optimax »

Yet another swapping method, using XOR, used for decades, not very fast, but odd enough.

Code: Select all


x = 2
y = 3
PRINT "let x = "; x
PRINT "let y = "; y
PRINT

'--- using < XOR >

PRINT "now XOR-SWAP"
PRINT
t1 = TIME$("ms")
FOR n = 1 TO 10001
	x = x XOR y
	y = y XOR x
	x = x XOR y
NEXT n
t2 = TIME$("ms")

PRINT "time = "; t2 - t1; " msec"
PRINT "now x = "; x
PRINT "now y = "; y
PRINT

'--- Terminate
PRINT "ENTER/RETURN to terminate..."; 
INPUT enter$
!QUIT
END