Main Content

Generate SIMD Code from MATLAB Algorithms in DSP System Toolbox

To generate SIMD code from MATLAB® System objects, create a coder.config (MATLAB Coder) object, set the CodeReplacementLibrary property to 'Intel AVX (Windows)' or 'Intel AVX (Linux)', and use it with the codegen (MATLAB Coder) command.

This workflow requires you to install MATLAB Coder™ and Embedded Coder® on your machine.

Consider this MATLAB function that filters a random multichannel signal using the dsp.FIRFilter System object™.

function y = firsingle()

persistent fir
if isempty(fir)
    b = fir1(250,.4);
    fir = dsp.FIRFilter(b);    
end

frameSize = 512;
numChannels = 8;
numFrames = 1e3;

for k = 1:numFrames
    x = randn(frameSize,numChannels,'single');
    y = fir(x);
end

Generate plain C code executable of this function using the codegen command.

cfg=coder.config('exe');
% provides starter main.c
cfg.GenerateExampleMain='GenerateCodeAndCompile';
if isunix
    codegen firsingle -config cfg -report -o firsingle_std    
elseif ispc
    codegen firsingle -config cfg -report -o firsingle_std.exe    
end

Measure the time it takes to run the generated executable.

tic; 
system('firsingle_std'); 
tplain = toc
tplain =

   1.2742

Generate AVX2 C code executable by setting the CodeReplacementLibrary parameter to 'Intel AVX (Windows)' or 'Intel AVX (Linux)', and calling the codegen command on the coder.config object.

cfg=coder.config('exe');
if isunix
    cfg.CodeReplacementLibrary = 'Intel AVX (Linux)';
elseif ispc 
    cfg.CodeReplacementLibrary = 'Intel AVX (Windows)';
end
% provides starter main.c
cfg.GenerateExampleMain='GenerateCodeAndCompile'; 
if isunix
    codegen firsingle -config cfg -report -o firsingle_avx2
elseif ispc
    codegen firsingle -config cfg -report -o firsingle_avx2.exe    
end

Measure the time it takes to run the generated executable.

tic; 
system('firsingle_avx2');
tavx2 = toc
tavx2 =

   0.3909

The generated SIMD code is around 3.3x faster compared to the plain C code on a Windows® 10 machine.

You can also generate a static library and a dynamic library by specifying the build type as 'lib' and 'dll', respectively.

cfg=coder.config('lib');
cfg.CodeReplacementLibrary='Intel AVX (Windows)';
codegen {FunctionName.m} -config cfg  
cfg=coder.config('dll');
cfg.CodeReplacementLibrary='Intel AVX (Windows)';
codegen {FunctionName.m} -config cfg

FunctionName.m is the MATLAB function that calls the System object you are trying to generate SIMD code from. For a list of System objects that support SIMD code generation, see System objects in DSP System Toolbox that Support SIMD Code Generation.

Related Topics