Some benchmarking about swapping two variables
Posted: Sat Jun 09, 2018 11:46 am
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.
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