Clear Filters
Clear Filters

Finding the time difference between both my functions

1 view (last 30 days)
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;

Accepted Answer

Adam
Adam on 20 Feb 2017
Edited: Adam on 20 Feb 2017
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.
  5 Comments
John D'Errico
John D'Errico on 20 Feb 2017
@Jan: tic and toc CAN work. The problem is most people who use tic and toc also fail to appreciate the other issues, like warmup time for a function to get it into cache, the need for multiple calls to average out tiny irregularities, etc.
As well, tic and toc also have issues with the parser and code optimization done by TMW. Code written at the command line may have different performance than code inside a function call. Of course, these things have changed with release.
Jan
Jan on 20 Feb 2017
Edited: Jan on 20 Feb 2017
@John: I agree, that timeit has advantages compared to tic/toc. I only wanted to remember, that anonymous functions can cause a remarkable overhead, which can impede the timings. See e.g. https://www.mathworks.com/matlabcentral/fileexchange/45749-memory-efficient-anonymous-functions.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!