# 的核数和进程_MATLAB并行计算之多进程连续滤波

function multiProcessFilter(objFilter,rawFile,processFile,M)
% 实现本地文件数据读取、多进程连续滤波、滤波后信号写入

% objFilter      1×1 dffir    FIR滤波器对象
% rawFile        1×n char     待滤波的二进制文件(int8)名称
% processFile    1×m char     滤波后的二进制文件(int8)名称
% M              1×1 double   进程数目,小于等于CPU核数

% FIR滤波器中寄存器个数
overlap  = length(objFilter.States);
% 打开要滤波的文件
fidWrite = fopen(processFile,'wb');
% 预处理一小段数据
preFilterData = filter(objFilter,preData);
fwrite(fidWrite,preFilterData,'int8');
% 文件读取不能多进程
% 多进程滤波
spmd(M)
id = labindex;
if isequal(id,1)
fdata = int8(fdata(overlap+1:end));
elseif isequal(id,M)
fdata = int8(fdata(overlap+1:end));
else
fdata = int8(fdata(overlap+1:end));
end
end
% 文件写入不能多进程操作
for ii = 1:M
fwrite(fidWrite,fdata{ii},'int8');
end
end
% 关闭文件
fclose('all');
end

function singleProcessFilter(objFilter,rawFile,processFile)
% PersistentMemory设为1，保持连续滤波
objFilter.PersistentMemory = 1;
fidWrite = fopen(processFile,'wb');

fdata = filter(objFilter,data);
fwrite(fidWrite,int8(fdata),'int8');
end
fclose('all');
end

function main()
% 68阶等纹波滤波器
objFilter = lowpassFilter;

% 单进程滤波
tic;singleProcessFilter(objFilter,'raw.bin','single.bin');toc
% 时间已过 138.555783 秒。

% parpool(6)
% 6进程滤波
tic;multiProcessFilter(objFilter,'raw.bin','multi.bin',6);toc
% 时间已过 46.245316 秒。

% 比较滤波结果
visdiff('single.bin','multi.bin','binary')
% 这些文件相同
end

function Hd = lowpassFilter
Fpass = 0.2;              % Passband Frequency
Fstop = 0.25;             % Stopband Frequency
Dpass = 0.057501127785;   % Passband Ripple
Dstop = 0.0031622776602;  % Stopband Attenuation
dens  = 20;               % Density Factor
[N, Fo, Ao, W] = firpmord([Fpass, Fstop], [1 0], [Dpass, Dstop]);
b  = firpm(N, Fo, Ao, W, {dens});
Hd = dfilt.dffir(b);
% set(Hd, 'Arithmetic', 'single');
end