之前写完的约束优化代码需要在十八个测试问题上跑完,由于随机性的影响,需要进行多次测试问题,耗时太久,所以需要用到matlab的并行计算的功能。
首先在matlab命令行中输入help parpool:
>> help parpool
parpool - Create parallel pool on cluster
This MATLAB function enables the full functionality of the parallel language
features (parfor and spmd) in MATLAB by creating a special job on a pool of
workers, and connecting the MATLAB client to the parallel pool.
parpool
parpool(poolsize)
parpool(profilename)
parpool(profilename,poolsize)
parpool(cluster)
parpool(cluster,poolsize)
parpool(___,Name,Value)
poolobj = parpool(___)
可以看出该函数目的是在集群上创建并行池,下面给出了函数用法;
parpool的参数profilename、poolsize、cluster均为可选,若不指定值则使用默认设置启动并行池,profilename是从指定配置文件建池,poolsize指定池的数量,最大数量与内核数有关,cluster从指定集群建池。
我将使用parpool('local', func)来通过本地配置文件构建大小为func的并行池。
在parpool的帮助描述中,提到的并行语言函数有parfor和spmd,parfor函数是parallel for的简写,用于在matlab中做并行循环;spmd函数是Single Program/Multiple Data的缩写,即单程序多任务并行。所以,本文将采用spmd函数作为接下来的计算。
在matlab命令行中输入help spmd:
>> help spmd
spmd - Execute code in parallel on workers of parallel pool
This MATLAB function defines an spmd statement on a single line.
spmd, statements, end
spmd(n), statements, end
spmd(m,n), statements, end
spmd的参数n、m均为可选,默认情况将使用并行池中所有的worker,如果没有可用的池,matlab将创建一个池并使用所有的worker。spmd(n)中参数n用于指定要计算的matlab worker的确切数量,spmd(m, n)中参数m,n表示worker个数的范围。
在spmd语句的statements中, 每个worker都有一个labindex的唯一值, 而numlabs表示并行执行该块的worker的总数。
由于我是对18个测试问题重复试验,故使用函数spmd(func),并且可以将参数labindex作为问题编号并行执行;
func = 2;
parpool('local', func);
spmd(func)
problem = labindex;
SRSeDEag
end
matlab给出了错误信息:错误使用 SRSeDEag (line 1),透明度违例错误。查找错误之后,将脚本文件SRSeDEag.m改成了函数,返回种群中最优值:
function [Best] = SRSeDEag(Problem)
错误使用 parpool (line 104)
Found an interactive session. You cannot have multiple interactive sessions open simultaneously. To terminate the existing session, use
'delete(gcp('nocreate'))'.
添加后上述代码后,程序测试通过,para_func.m脚本最终为:
delete(gcp('nocreate'));
func = 18;
parpool('local', func);
spmd(func)
problem = labindex;
Best = SRSeDEag(problem);
end
1. spmd函数返回类型为composite,通过Best{problem}来访问;
2. 修改默认的local并行池的个大小:主页->环境->Parallel->Manage Cluster Profiles->local(default)->Edit->Properties->Number of workers to start on your local machine,我的修改成18即可。