# 从桌面扩展到集群

### 开发您的算法

```primeNumbers = primes(uint64(2^21)); compositeNumbers = primeNumbers.*primeNumbers(randperm(numel(primeNumbers))); factors = zeros(numel(primeNumbers),2);```

```tic; for idx = 1:numel(compositeNumbers) factors(idx,:) = factor(compositeNumbers(idx)); end toc```
```Elapsed time is 684.464556 seconds. ```

### 在本地并行池上运行代码

Parallel Computing Toolbox™ 使您能够通过在并行池中运行多个工作进程来扩展工作流。前一个 `for` 循环中的迭代是独立的，因此您可以使用 `parfor` 循环将迭代分配给多个工作进程。只需将 `for` 循环转换为 `parfor` 循环。然后，运行代码并测量总体计算时间。代码在并行池中运行，无需进一步更改，然后工作进程将您的计算发送回本地工作区。由于工作量分布在多个工作进程身上，因此计算时间较短。

```tic; parfor idx = 1:numel(compositeNumbers) factors(idx,:) = factor(compositeNumbers(idx)); end toc```
```Elapsed time is 144.550358 seconds. ```

```numWorkers = [1 2 4 6]; tLocal = zeros(size(numWorkers));```

```for w = 1:numel(numWorkers) tic; parfor (idx = 1:numel(compositeNumbers), numWorkers(w)) factors(idx,:) = factor(compositeNumbers(idx)); end tLocal(w) = toc; end```

```f = figure; speedup = tLocal(1)./tLocal; plot(numWorkers, speedup); title('Speedup with the number of workers'); xlabel('Number of workers'); xticks(numWorkers); ylabel('Speedup');```

`delete(gcp);`

### 在集群并行池上运行您的代码

`parpool('MyCluster',64);`
```Starting parallel pool (parpool) using the 'MyCluster' profile ... connected to 64 workers. ```

```numWorkers = [1 2 4 6 16 32 64]; tCluster = zeros(size(numWorkers)); for w = 1:numel(numWorkers) tic; parfor (idx = 1:numel(compositeNumbers), numWorkers(w)) factors(idx,:) = factor(compositeNumbers(idx)); end tCluster(w) = toc; end```

```figure(f); hold on speedup = tCluster(1)./tCluster; plot(numWorkers, speedup); title('Speedup with the number of workers'); xlabel('Number of workers'); xticks(numWorkers(2:end)); ylabel('Speedup');```

`delete(gcp);`

### 使用 `batch` 卸载和扩展您的计算

```totalNumberOfWorkers = 65; cluster = parcluster('MyCluster'); job = batch(cluster,'myParallelAlgorithmFcn',2,'Pool',totalNumberOfWorkers-1,'CurrentFolder','.');```

`wait(job);`

```outputs = fetchOutputs(job); numWorkers = outputs{1}; time = outputs{2};```

```figure speedup = time(1,:)./time; plot(numWorkers,speedup); legend('Problem complexity 1','Problem complexity 2','Problem complexity 3','Problem complexity 4','Location','northwest'); title('Speedup vs complexity'); xlabel('Number of workers'); xticks(numWorkers(2:end)); ylabel('Speedup');```