Effacer les filtres
Effacer les filtres

Methods in Making a Simple Program More Efficient

2 vues (au cours des 30 derniers jours)
David C
David C le 30 Mai 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

Réponse acceptée

per isakson
per isakson le 30 Mai 2013
Modifié(e) : per isakson le 30 Mai 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 commentaires
Sean de Wolski
Sean de Wolski le 30 Mai 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 le 31 Mai 2013
Thanks to you both for these great ideas!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by