code is running too long, help me to optimize it
10 次查看(过去 30 天)
显示 更早的评论
I have written a code, it runs slow. I don't know if it is because of the code or just it should take so long because of the number of loops and calculations.
can you help me to check/improve it please.
采纳的回答
Jan
2019-2-26
Start with inserting the code in a function, instead of using a script and try to use clear all to kill everything, which might be out of sight. This is a massive waste of time only.
Then mark the code with Ctrl-a and press Ctrl-i to apply a proper auto-indentation. This does not make the code faster, but much easier to debug. A lot of meaningful comments are essential also: Without it other readers cannot understand the purpose of the code- or you in some months. If I should work with this code, I'd give up immediately, because it is impossible to debug blocks like this:
Tc(jj) = Tc(jj-1)+dTc(jj-1);
Tt(jj)=Tt(jj-1)+dTt(jj-1);
Twout(jj)=Twout(jj-1)+dTwout(jj-1);
Tw(jj)=Tw(jj-1)+dTw(jj-1);
Tg1(jj) = Tg1(jj-1)+dTg1(jj-1);
Tadt(jj) = Tadt(jj-1)+dTadt(jj-1);
Tadb(jj) = Tadb(jj-1)+dTadb(jj-1);
t(jj)=t(jj-1)+1;
Ub(jj)=Ub(jj-1);
For the actual problem use the profiler to find the bottleneck: Which line needs the most processing time? It is not worth to optimze some code, which takes a few percent of the total time only.
It is not called often in your code, but remember that 10.^-5 is an expensive power operation, while 1e-5 is a cheap constant.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!