Convertfor
-Loops Intoparfor
-Loops
In some cases, you must modify the code to convertfor
- 环parfor
-loops. This example shows how to diagnose and fixparfor
-loop problems using a simple nestedfor
-环形。Run this code in MATLAB®和examine the results.
forx = 0:0.1:1fory = 2:10 A(y) = A(y-1) + y;endend
To speed up the code, try to convert thefor
- 环parfor
-loops. Observe that this code produces errors.
parforx = 0:0.1:1parfory = 2:10 A(y) = A(y-1) + y;endend
In this case you cannot simply convert thefor
- 环parfor
-loops without modification. To make this work, you must change the code in several places. To diagnose the problems, look for Code Analyzer messages in the MATLAB Editor.
当您尝试转换时,此代码显示了常见的问题for
- 环parfor
-loops.
To solve these problems, you must modify the code to useparfor
。The body of theparfor
-loop is executed in a parallel pool using multiple MATLAB workers in a nondeterministic order. Therefore, you have to meet these requirements for the body of theparfor
-loop:
The body of the
parfor
-loop must be independent. One loop iteration cannot depend on a previous iteration, because the iterations are executed in parallel in a nondeterministic order. In the example,A(y) = A(y-1) + y;
parfor
。下一步的处理with independence issues, seeEnsure That parfor-Loop Iterations are Independent。You cannot nest a
parfor
- 在另一个parfor
-环形。The example has two nestedfor
-loops, and therefore you can replace only onefor
-loop with aparfor
-环形。Instead, you can call a function that uses aparfor
-loop inside the body of the otherparfor
-环形。但是,这样的嵌套parfor
-loops give you no computational benefit, because all workers are used to parallelize the outermost loop. For help dealing with nested loops, seeNested parfor and for-Loops and Other parfor Requirements。parfor
-loop variables must be consecutive increasing integers. In the example,parforx = 0:0.1:1
parfor
here. You can solve this problem by changing the value of the loop variable to integer values required by the algorithm. For next steps in troubleshootingparfor
-loop variables, seeEnsure That parfor-Loop Variables Are Consecutive Increasing Integers。You cannot break out of a
parfor
-loop early, as you can in afor
-环形。Do not include a return or break statement in the body of yourparfor
-环形。Without communication, the other MATLAB instances running the loop do not know when to stop. As an alternative, considerparfeval
。If you still have problems converting
for
- 环parfor
-loops, see对parfor-loops中的变量进行故障排除。
Tip
You can profile aparfor
-loops usingtic
和toc
to measure the speedup compared to the correspondingfor
-环形。UseticBytes
和tocBytes
to measure how much data is transferred to and from the workers in the parallel pool. For more information and examples, see剖析parfor-loops。