MATLAB Answers

parfor slower than for

조회 수: 37(최근 30일)
Qammar Abbas
Qammar Abbas 2021년 9월 20일 15:26
댓글: Qammar Abbas 2021년 9월 21일 19:58
Hi Community members,
I am trying to run a very simple parfor loop and a for loop to compare results. However, to my surprise parfor is almost 100 times slower than for loop. Can anyone please explain this? I intend to run a code with almost 10000000000 iterations and need to decide how to make it fastest. Your suggestions will be very helpful in this regard.
arr=[];
tic
parfor x=1:50
arr(x) = x;
end
toc
Elapsed time is 0.385357 seconds.
arr=[];
tic
for x=1:50
arr(x) = x;
end
toc
Elapsed time is 0.004795 seconds.

답변(2개)

Raymond Norris
Raymond Norris 2021년 9월 20일 15:40
There are several considerations
  • How many dedicated workers? Most often, more workers, the lower the amount of time.
  • Amount of time to run the unit of work. Does it take more time to send the code then to run the code?
Your example is trivial. If your code really takes 0.005s to run all your sims, then parfor is not needed. Conversely, here's a better trivial example
tic
parfor idx = 1:50
pause(2)
end
toc
  댓글 수: 5
Qammar Abbas
Qammar Abbas 2021년 9월 21일 19:58
For more details, please see the Actual problem I posted.

댓글을 달려면 로그인하십시오.


Jan
Jan 2021년 9월 20일 15:53
The main work in you example is the iterative growing of the array. This is a waste of time in sequential and parallel code. Pre-allocate the output properly.
Starting parallel threads must take some time. For such a trivial code, the overhead is expected to be higher than the payload. Compare this with instructing 8 people to say the numbers 1 to 50. It is much faster to do this by your own.
  댓글 수: 3
Steven Lord
Steven Lord 2021년 9월 20일 18:08
There's more information on the poster's actual use case in this other Answers post.

댓글을 달려면 로그인하십시오.

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by