nelson-lang / nelson

The Nelson Programming Language
https://nelson-lang.github.io/nelson-website/
GNU Lesser General Public License v3.0
94 stars 17 forks source link

Recursive functions are rather slow #1067

Open rdbyk opened 10 months ago

rdbyk commented 10 months ago

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.

Nelson-numerical-software commented 10 months ago

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 !!!

Nelson-numerical-software commented 10 months ago

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
Nelson-numerical-software commented 10 months ago

for v1.0 basic optimization: image

Nelson-numerical-software commented 10 months ago

to test:

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