Finding the time difference between both my functions

1 次查看(过去 30 天)
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;

采纳的回答

Adam
Adam 2017-2-20
编辑:Adam 2017-2-20
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 个评论
John D'Errico
John D'Errico 2017-2-20
@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 2017-2-20
编辑:Jan 2017-2-20
@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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by