Borrar filtros
Borrar filtros

Finding the time difference between both my functions

1 visualización (últimos 30 días)
Jack Zimmerman
Jack Zimmerman el 20 de Feb. de 2017
Editada: Jan el 20 de Feb. de 2017
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;

Respuesta aceptada

Adam
Adam el 20 de Feb. de 2017
Editada: Adam el 20 de Feb. de 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 comentarios
John D'Errico
John D'Errico el 20 de Feb. de 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 el 20 de Feb. de 2017
Editada: Jan el 20 de Feb. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by