When to Use parfor

parfor-Loops in MATLAB

The basic concept of a parfor-loop in MATLAB® software is the same as the standard MATLAB for-loop: MATLAB executes a series of statements (the loop body) over a range of values. The MATLAB client (where the parfor is issued) coordinates with MATLAB workers comprising a parallel pool, so that the loop iterations can be executed in parallel on the pool. The necessary data on which parfor operates is sent from the client to workers, where most of the computation happens, and the results are sent back to the client and pieced together.

Because several MATLAB workers can be computing concurrently on the same loop, a parfor-loop can provide significantly better performance than its analogous for-loop.

Each execution of the body of a parfor-loop is an iteration. MATLAB workers evaluate iterations in no particular order, and independently of each other. Because each iteration is independent, there is no guarantee that the iterations are synchronized in any way, nor is there any need for this. If the number of workers is equal to the number of loop iterations, each worker performs one iteration of the loop. If there are more iterations than workers, some workers perform more than one loop iteration; in this case, a worker might receive multiple iterations at once to reduce communication time.

Deciding When to Use parfor

A parfor-loop is useful in situations where you need many loop iterations of a simple calculation, such as a Monte Carlo simulation. parfor divides the loop iterations into groups so that each worker executes some portion of the total number of iterations. parfor-loops are also useful when you have loop iterations that take a long time to execute, because the workers can execute iterations simultaneously.

You cannot use a parfor-loop when an iteration in your loop depends on the results of other iterations. Each iteration must be independent of all others. Since there is a communications cost involved in a parfor-loop, there might be no advantage to using one when you have only a small number of simple calculations. The examples of this section are only to illustrate the behavior of parfor-loops, not necessarily to show the applications best suited to them.

Related Examples

More About

Was this topic helpful?