Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

parfor

Execute for-loop iterations in parallel on workers in parallel pool

Syntax

parfor loopVar = initVal:endVal; statements; end
parfor (loopVar = initVal:endVal, M); statements; end

Description

example

parfor loopVar = initVal:endVal; statements; end executes for-loop iterations in parallel on workers in a parallel pool.

MATLAB® executes the loop body commands in statements for values of loopVar between initVal and endVal. loopVar specifies a vector of integer values increasing by 1. If you have Parallel Computing Toolbox™, the iterations of statements can execute on a parallel pool of workers on your multi-core computer or cluster. As with a for-loop, you can include a single line or multiple lines in statements.

To find out how parfor can help increase your throughput, see Decide When to Use parfor.

parfor differs from a traditional for-loop in the following ways:

  • Loop iterations are executed in parallel in a nondeterministic order. This means that you might need to modify your code to use parfor. For more help, see Convert for-Loops Into parfor-Loops.

  • Loop iterations must be consecutive increasing integer values.

  • The body of the parfor-loop must be independent. One loop iteration cannot depend on a previous iteration, because the iterations are executed in a nondeterministic order. For more help, see Ensure That parfor-Loop Iterations are Independent.

  • You cannot use a parfor-loop inside another parfor-loop. For more help, see Nested parfor-Loops and for-Loops.

example

parfor (loopVar = initVal:endVal, M); statements; end uses M to specify the maximum number of workers from the parallel pool to use in evaluating statements in the loop body. M must be a nonnegative integer.

By default, MATLAB uses the available workers in your parallel pool. You can change the number of workers on the Home tab in the Environment section, select Parallel > Parallel Preferences. You can override the default number of workers in a parallel pool by using parpool. When no workers are available in the pool or M is zero, MATLAB still executes the loop body in a nondeterministic order, but not in parallel.

To execute the iterations in parallel, you must have a parallel pool of workers. By default, if you execute parfor, you automatically create a parallel pool of workers on the cluster defined by your default cluster profile. The default cluster is local. You can change your cluster in Parallel Preferences. For more details, see Specify Your Parallel Preferences.

Examples

collapse all

Create a parfor-loop for a computationally intensive task. Measure the resulting speedup and data transferred to and from the workers in the parallel pool..

In the MATLAB Editor, enter the following for-loop. To measure the time elapsed, add tic and toc.

tic
n = 200;
A = 500;
a = zeros(n);
for i = 1:n
    a(i) = max(abs(eig(rand(A))));
end
toc

Run the script, and note the elapsed time.

Elapsed time is 31.935373 seconds.

In the script, replace the for-loop with a parfor-loop. Add ticBytes and tocBytes to measure how much data is transferred to and from the workers in the parallel pool.

tic
ticBytes(gcp);
n = 200;
A = 500;
a = zeros(n);
parfor i = 1:n
    a(i) = max(abs(eig(rand(A))));
end
tocBytes(gcp)
toc

Run the new script, and run it again. The first run is slower than the second run, because the parallel pool has to be started, and you have to make the code available to the workers. Note the elapsed time for the second run.

By default, MATLAB automatically opens a parallel pool of workers on your local machine.

Starting parallel pool (parpool) using the 'local' profile ... connected to 4 workers.
...
             BytesSentToWorkers    BytesReceivedFromWorkers
             __________________    ________________________

    1        15340                  7024                   
    2        13328                  5712                   
    3        13328                  5704                   
    4        13328                  5728                   
    Total    55324                 24168                   

Elapsed time is 10.760068 seconds. 

Observe that you speed up your calculation by converting the for-loop into a parfor-loop on four workers. You might reduce the elapsed time further by increasing the number of workers in your parallel pool, see Scale Up parfor-Loops to Cluster and Cloud.

Specify the maximum number of workers for a parfor-loop.

Write a MATLAB function, specify_num_workers, that uses input, w, to specify the maximum number of workers in the parfor-loop.

function y = specify_num_workers(w)
  y = ones(1,100);
  % w specifies maximum number of workers
  parfor (i = 1:100,w)
    y(i) = i;
  end
end

In this example, specify a number of workers. The default cluster is your local machine. If you request more workers than the maximum number on your default cluster, then you get allocated the maximum number of workers available:

specify_num_workers(64);
Starting parallel pool (parpool) using the 'local' profile ... connected to 4 workers.
To learn how to increase the number of workers in your parallel pool, see Scale Up parfor-Loops to Cluster and Cloud.

Input Arguments

collapse all

Loop index variable with initial value initVal and final value endVal. The variable can be any numeric type and the value must be an integer.

Make sure that your parfor-loop variables are consecutive increasing integers. For more help, see Troubleshoot Variables in parfor-Loops.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Initial value loop index variable, loopvar. The variable can be any numeric type and the value must be an integer. With endVal, specifies the parfor range vector, which must be of the form M:N.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Final value loop index variable, loopVar. The variable can be any numeric type and the value must be an integer. With initVal, specifies the parfor range vector, which must be of the form M:N.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Loop body, specified as text. The series of MATLAB commands to execute in the parfor-loop.

You might need to modify your code to use parfor-loops. For more help, see Convert for-Loops Into parfor-Loops

Do not nest parfor-loops, see Nested parfor-Loops and for-Loops.

Maximum number of workers running in parallel, specified as a nonnegative integer. If you specify an upper limit, MATLAB uses no more than this number, even if additional workers are available. If you request more workers than the number of available workers, then MATLAB uses the maximum number of workers available at the time of the call. If the loop iterations are fewer than the number of workers, some workers perform no work.

If parfor cannot run on multiple workers (for example, if only one core is available or M is 0), MATLAB executes the loop in a serial manner.

Tips

  • Use a parfor-loop when:

    • You have many loop iterations of a simple calculation. parfor divides the loop iterations into groups so that each thread can execute one group of iterations.

    • You have some loop iterations that take a long time to execute.

  • Do not use a parfor-loop when an iteration in your loop depends on the results of other iterations.

    Reductions are one exception to this rule. A reduction variable accumulates a value that depends on all the iterations together, but is independent of the iteration order. For more information, see Reduction Variables.

  • When you use parfor, you have to wait for the loop to complete to obtain your results. Your client MATLAB is blocked and you cannot break out of the loop early. If you want to obtain intermediate results, or break out of a for-loop early, try parfeval instead.

  • A parfor-loop runs on the existing parallel pool. If no pool exists, parfor starts a new parallel pool, unless the automatic starting of pools is disabled in your parallel preferences. If there is no parallel pool and parfor cannot start one, the loop runs serially in the client session.

  • If the AutoAttachFiles property in the cluster profile for the parallel pool is set to true, MATLAB performs an analysis on a parfor-loop to determine what code files are necessary for its execution, see listAutoAttachedFiles. Then MATLAB automatically attaches those files to the parallel pool so that the code is available to the workers.

  • You cannot call scripts directly in a parfor-loop. However, you can call functions that call scripts.

  • Do not use clear inside a parfor loop because it violates workspace transparency. See Ensure Transparency in parfor-Loops.

  • You can run Simulink® models in parallel with the parsim command instead of using parfor-loops. For more information and examples of using Simulink in parallel, see Run Multiple Simulations (Simulink).

Introduced in R2008a

Was this topic helpful?