Methods in Making a Simple Program More Efficient

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

Accepted Answer

per isakson
per isakson on 30 May 2013
Edited: per isakson on 30 May 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 Comments
Sean de Wolski
Sean de Wolski on 30 May 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 on 31 May 2013
Thanks to you both for these great ideas!

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!