How to reduce For loop execution time?
2 ビュー (過去 30 日間)
古いコメントを表示
I have following Matlab code to calculate summation of exponential summation term:
This code takes approx. 600 seconds to give final output s. Is there any way to reduce this computation time?
sum1 = 0;
s = 0;
for i=1:1000000000
for j=1:3
sum1 = sum1+(i*proc(j))^2;
end
s = s+exp(-sum1);
end
7 件のコメント
Steven Lord
2019 年 12 月 5 日
What is the mathematical (not code) expression of what you're trying to compute with this code? Or do you have a description in words of what you're trying to compute? That might help us understand what the right result is and find an efficient way to compute that right result.
Also, what are the contents of the variable proc? When you get to the last iterations of the outer loops, you're adding an extremely large number to sum1 unless the elements of proc are very small. You might be able to stop the outer loop sooner if sum1 is so large that exp(-sum1) underflows to 0.
y = 750;
exp(-y) % 0
採用された回答
Walter Roberson
2019 年 12 月 5 日
>> tic;s = sum(exp(-sum((reshape(proc(1:3), [], 1) * (1:1000000000)).^2))); toc
Elapsed time is 55.136908 seconds.
This was slowed down a fair bit because I ran out of memory and it started to swap. On my system, if I had run it in 10 sections of 1E8 the time would have been less than 20 seconds.
6 件のコメント
Walter Roberson
2019 年 12 月 7 日
I notice that the contribution of each element does not go down to eps until you reach 4743809974903 which is greater than 2^42. Even if you break it up into segments to avoid memory overflow, that is a lot of calculations. If we approximate being able to do 2^30 values per second (e.g., 3-ish GHz CPU and suppose somehow it only took 3 clock cycles per value) then it would take 2^12 = 4096 seconds. My measured speed on my system is more on the order of 4.6E-8 seconds per iteration, approximately 218215 seconds = about 60 hours.
その他の回答 (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!