Methods in Making a Simple Program More Efficient

1 visualización (últimos 30 días)
David C
David C el 30 de Mayo de 2013
Hi,
I would like to speed up the execution of my program. It's abbreviated as follows:
Definition of myScript.m is as follows:
%start of myScript.m
...
for m=1:1000
myFunction(m)
end
...
%end of myScript.m
Definition of myFunction(m):
%start of myFunction.m
function output=myFunction(m)
... %code that uses m
internalVar=takeALongTimeFunction() %does not use m
end
%end of myFunction.m
The function takeALongTimeFunction() does not have an input argument, takes a long time to execute, and returns the same result for each call to myFunction(m). How can I speed up the execution of the entire program?
Thanks,
David

Respuesta aceptada

per isakson
per isakson el 30 de Mayo de 2013
Editada: per isakson el 30 de Mayo de 2013
Try
clear takeALongTimeFunction
tic, takeALongTimeFunction, toc
tic, takeALongTimeFunction, toc
it should return something like
ans =
17
Elapsed time is 7.004011 seconds.
ans =
17
Elapsed time is 0.000456 seconds.
where
function out = takeALongTimeFunction()
persistent result_of_last_time
if not( isempty( result_of_last_time ) )
out = result_of_last_time;
return
end
out = 17;
pause( 7 )
result_of_last_time = out;
end
  2 comentarios
Sean de Wolski
Sean de Wolski el 30 de Mayo de 2013
I would even suggest saving the result to disk, then if the persistent variable is empty && and the matfile with the result doesn't exist, then do the computation.
David C
David C el 31 de Mayo de 2013
Thanks to you both for these great ideas!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by