Modern CPUs are normally equipped with multi-cores, but to take full advantage it for your Matlab program you normally require the parallel computing toolbox. Fortunately, you have other option too. For this article, we will look into using the OpenMP to achieve the speed up you are looking for. OpenMP provides API for shared-memory parallel programming in C/C++ and Fortran. It supports multiple platform (Windows, Linux, MacOS), which is a perfect candidate.

Before proceed with the post, you would need to install the C compiler for MEX. Here is a list of compatible C/C++ compiler for Matlab. For my case, I am using the MinGW in Windows Platform.

Step 1: Add the OpenMP pragma in the C code

The first step is to modify the C code to let OpenMP know where it should pitch in to perform the parallel computing. For more instructions on how to use the OpenMP, you can refer to their official website. In this post, I will only demonstrate with a simple example for the procedure.

In the place where the parallel suppose to happen, add the statement similar to this.

The full example code (test_openmp.c) for this post is below. The function is to do a whole bunch of add operation to each elements of the temp[6] array, then the sum of 6 elements are output. We instruct it to do parallel computing for variable i.

Step 2: Compile the C file using Mex

There is some small dependency on the platform and C compiler you are using.

2.1 Running in Windows OS

2.1.1 Using MSVC for Mex

For MSVC on Windows, add /openmp to the compilation flags:

2.1.1 Using MinGW for Mex

For MinGW in Windows, add

2.2 Running in Linux OS

For GCC on Linux systems, add -fopenmp to both CFLAGS and LDFLAGS:

Of course, we can also use the Makefile to compile the C code instead of in the Mex. The

need to be added into the gcc flags.

2.3 Set the OPM_NUM_THREAD

You can either set it in Matlab or in the environment variable.

Set it in Matlab

Set it using environment variable

For example in Linux OS, before run the Matlab:

Step 3: Test the Function

I am using MinGW-w64 (version 19.1.0) with Matlab R2019a in Windows 10.

Here is a comparison of using OpenMP vs not using OpenMP

With OpenMP (MinGW example)

Here is the result for the run:

Without OpenMP (MinGW example)

Here is the result for the run:

The speed up from the OpenMP is apparent (5X). Enjoy it.

How to Enable OpenMP for Mex Function in Matlab
Tagged on:     

Please tell us what's in your mind ...

%d bloggers like this: