'Efficient parallelization of two tasks

I have two tasks that take a fairly short time to compute (around half a second each). These two tasks (say A and B) are called repeatedly a large number of times. Each time they are called, the two tasks can be computed in parallel because they don't depend on each other. Here is an example code without parallelization:

A = 3;
B = 4;

for counter = 1:5000

A = task1(counter,A); %Run task 1
B = task2(counter,B); %Run task 2

disp(task3(A,B)); %Use the results for task 3
end

The most obvious way to parallelize this on MATLAB is to do the following:

A = 3;
B = 4;

pool = parpool("threads");
for counter = 1:5000

parfor p = 1:2
if p == 1
A = task1(counter,A); %Run task 1
end
if p == 2
B = task2(counter,B); %Run task 2
end

disp(task3(A,B)); %Use the results for task 3
end
delete('pool')

This implementation, however, turns out to be much slower (almost by 10 times). My guess is that this is the result of overhead issues involved in parallelization.

Is there any way to go around this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source