nelson icon indicating copy to clipboard operation
nelson copied to clipboard

Recursive functions are rather slow

Open rdbyk opened this issue 1 year ago • 4 comments

function x = fib(n) if n < 2 x = n; else x = fib(n-1) + fib(n-2); end endfunction

in Nelson 0.7.12.0

tic;fib(25);toc Elapsed time is 20.999976 seconds.

in Balisc/Scilab

--> tic;fib(25);toc ans =

0.5551460

-->

It is not important to me, but I was just a little bit surprised, anyway I really like the evolution of Nelson.

rdbyk avatar Dec 30 '23 18:12 rdbyk

Hi, recursive functions will be fixed with version 2.0 (I began to rewrite current interpreter to increase compatibility and speed x100 on loop and recursive call ;) ) I will check on v1.x if it is possible to do better with existing interpreter. True performance will come with v2 :)

Contributions and feedbacks are welcome !!!

fibonacci recursive algo can be converted to non-recursive:

function last_fibonacci = fib2(n)
    fib_sequence = zeros(1, n);
    fib_sequence(1) = 1;
    fib_sequence(2) = 1;

    for i = 3:n
        fib_sequence(i) = fib_sequence(i-1) + fib_sequence(i-2);
    end

    last_fibonacci = fib_sequence(end);
end
Elapsed time is 0.005784 seconds.
>> r

r =

       75025

for v1.0 basic optimization: image

to test:

>> addpath('d:/')
>> timeit(@fib, 1, 25)