parfor is slower than for
Show older comments
Dear Matlab community, I am trying to implement parfor function and have 5000 iterations. What kind of settings and preferences should I select? looking at different resources I did such commands:
parpool(8)
Result:
Connected: true
NumWorkers: 8
Cluster: local
AttachedFiles: {}
IdleTimeout: 30 minutes (30 minutes remaining)
SpmdEnabled: true
Then I run a function:
clc;
clear;
modulation = 4;
iterations = 5000;
tic
parfor i=1:iterations
if(modulation == 4)
result(1,i) = modulation*i;
elseif(modulation == 16)
result(1,i) = 2*modulation*i;
end
end
time_1 = toc;
tic
for i=1:1:iterations
if(modulation == 4)
result(1,i) = modulation*i;
elseif(modulation == 16)
result(1,i) = 2*modulation*i;
end
end
time_2 = toc;
fprintf('time Parallel = %.9f;\n', time_1);
fprintf('time Serial = %.9f;', time_2);
fprintf('\n');
Result time is as following: time Parallel = 0.150103298; time Serial = 0.000062877;
How to improve parallel run time?
Thank you
4 Comments
"parfor is slower than for"
"How to improve parallel run time?"
Why do you think that parfor should be faster than for for your problem? It is not the case that parfor is always faster. Have you read the MATLAB documentation on this?:
Talgat Manglayev
on 19 Mar 2018
You need to consider the actual problem you want to solve when it comes to parallelisation. Creating a simple example is fine for understanding syntax and some of the warnings and errors about variable classification you may get, but for simply looking at the speed it is erroneous.
In your example was the parallel pool already open before the parfor loop? If not then this takes time to open. Even if it is data has to be copied to the workers.
Your serial process took 0.000062877s in this case. Just how fast do you want this to be???!!!! Do you really expect that copying data to multiple workers would be faster than that? That serial time is so fast I can't even be bothered to work out how to say that time in words!
From the link Stephen posted:
A parfor-loop might not be useful if you have:
Code that has vectorized out the for-loops. Generally, if you want to make code run faster, first try to vectorize it. For details how to do this, see Vectorization (MATLAB). Vectorizing code allows you to benefit from the built-in parallelism provided by the multithreaded nature of many of the underlying MATLAB libraries. However, if you have vectorized code and you have access only to local workers, then parfor-loops may run slower than for-loops. Do not devectorize code to allow for parfor; in general, this solution does not work well.
Loop iterations that take a short time to execute. In this case, parallel overhead dominates your calculation.
Accepted Answer
More Answers (0)
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!