Main Content

Interactively Run a Loop in Parallel Usingparfor

In this example, you start with a slowfor-loop, and you speed up the calculation using aparfor-loop instead.parforsplits the execution offor-loop iterations over the workers in a parallel pool.

This example calculates the spectral radius of a matrix and converts afor-loop into aparfor-loop. Find out how to measure the resulting speedup.

  1. In the MATLAB®Editor, enter the followingfor-loop. Addticandtocto measure the time elapsed.

    tic n = 200; A = 500; a = zeros(n);fori = 1:n a(i) = max(abs(eig(rand(A))));endtoc
  2. Run the script, and note the elapsed time.

    Elapsed time is 31.935373 seconds.

  3. In the script, replace thefor-loop with aparfor-loop.

    tic n = 200; A = 500; a = zeros(n);parfori = 1:n a(i) = max(abs(eig(rand(A))));endtoc

  4. Run the new script, and run it again. Note that the first run is slower than the second run, because the parallel pool takes some time to start and 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. ... Elapsed time is 10.760068 seconds.
    Theparforrun on four workers is about three times faster than the correspondingfor循环运行。加速比的小理想speed-up of a factor of four on four workers. This is due to parallel overhead, including the time required to transfer data from the client to the workers and back. This example shows a good speed-up with relatively small parallel overhead, and benefits from conversion into aparfor-loop. Not allfor-loop iterations can be turned into fasterparfor-loops. To learn more, seeDecide When to Use parfor.

One key requirement for usingparfor-loops is that the individual iterations must be independent. Independent problems suitable forparfor处理包括蒙特卡洛模拟和参数扫描。对于下一步,请参阅Convert for-Loops Into parfor-Loops.

In this example, you managed to speed up the calculation by converting thefor-loop into aparfor-loop on four workers. You might reduce the elapsed time further by increasing the number of workers in your parallel pool, seeScale Up parfor-Loops to Cluster and Cloud.

You can modify your cluster profiles to control how many workers run your loops, and whether the workers are local or on a cluster. For more information on profiles, seeDiscover Clusters and Use Cluster Profiles.

Modify your parallel preferences to control whether a parallel pool is created automatically, and how long it remains available before timing out. For more information on preferences, seeSpecify Your Parallel Preferences.

You can run Simulink®models in parallel with theparsimcommand instead of usingparfor-loops. For more information and examples of using Simulink in parallel, see运行多个模拟(Simulink).

See Also

|||

相关话题