Methods in Making a Simple Program More Efficient

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

采纳的回答

per isakson
per isakson 2013-5-30
编辑:per isakson 2013-5-30
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 个评论
Sean de Wolski
Sean de Wolski 2013-5-30
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.

请先登录,再进行评论。

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by