Fibonacci benchmark

Questions about the BASICtools and MakeItC
Post Reply
YahooArchive
Posts: 1462
Joined: Fri Oct 19, 2012 5:11 am

Fibonacci benchmark

Post by YahooArchive »

One of the standard benchmarks people use is a recursive calculation of
fibonacci numbers. Normally ARMbasic does not support recursion, but it
can be done by building your own stack. As there were only 100 other
things I needed to do today, I wrote this test program instead.

Anyway I knew this would be klunky and probably slow, I tried anyway.

fibo(29) done in 3.2 seconds
As I knew the BASIC call could be improved I tweaked the runtime a bit
and got it below 3 seconds.

Just for reference in C this takes 0.33 seconds. Obviously C is using
the built in stack and dedicated registers, so its much faster. The
reason BASIC is not using the same mechanism is to keep the stack usage
low, and keeps its own pointers to the BASIC return stack in RAM.

Anyway here is the program I wrote, which maintains its own stack.

dim stack(64)

' C version
'int fib (int x) {
' if (x > 2) return fib(x-1)+fib(x-2);
' return 1;
'}


' on each call
' stack(sp) = x
' stack(sp+1) = fib (x-1)
' fibo is set on return

dofib:
if (x > 2) then

stack(sp) = x
sp = sp + 2

x = x - 1
gosub dofib ' fib(x -1)
stack(sp-1) = fibo

x = x - 1
gosub dofib ' fib(x -2)

fibo = fibo + stack(sp-1) ' set the return value
sp = sp - 2 ' restore stack
x = stack(sp) ' restore the x value

return

endif

fibo = 1
return



main:
fibo = 0
sp = 0
x = 29
gosub dofib
print fibo



Post Reply