MATLAB: Finding the time difference between both the functions

function timing

These are my 2 functions, is there a way of putting them into a script and comparing their running times?
function nprimes(N)
n = 1;
nPrimes = 0;
while nPrimes < N
if isprime(n)
fprintf('%i\n',n)
nPrimes = nPrimes + 1;
end
n = n + 1;
end
end
function p = nprimes(N)
p = [];
if N == 1
p = 2;
elseif N == 2
p = [2 3];
else
pn1 = nprimes(N-1);
plast = pn1(end) + 1;
while ~isprime(plast)
plast = plast + 1;
end;
p = [nprimes(N-1), plast];
end;

Best Answer

If you put them in a single file (obviously with different names) that starts with a function (name it whatever you want, but it has to be a function, not a script in this case) then e.g.
function compareTimes( )
N = 27;
t1 = timeit( @( ) nprimes1( N ) )
t2 = timeit( @( ) nprimes2( N ) )
end
function nprimes1( N )
...
end
function nprimes2( N )
...
end
You can just use nested functions if you prefer, though I wouldn't do this in this case if you are trying to test the function with an argument passed in rather than in a context where it shares its workspace with some other function that won't be there in a general context.