MATLAB: Is the MEX file I generated from the MATLAB code slower than the MATLAB code

coderMATLABmatlab codermexspeed

I expect that creating a MEX file from my MATLAB code should always provide a speed improvement. Why is this not the case?

Best Answer

It is important to remember that under the hood, a MEX file is simply a function that calls a C/C++ (or sometimes Fortran) subroutine. So when we are comparing the execution time of a MATLAB script to that of a MEX file, we are comparing the amount of time it takes the MATLAB script to be interpreted to the amount of time it takes the generated C/C++ code to execute.
Now it is reasonable to think that compiled C code should execute faster than M code is interpreted. However, it has been many years since MATLAB has been a true interpreted language. Today it is a just-in-time (JIT) compiled language with a large library of pre-compiled routines that are optimized for the target that MATLAB is running on. With MEX code generation, we are generating portable C code. Sometimes the MATLAB libraries are even multi-threaded while the generated code is not. Generally speaking, when an application mostly exercises pre-compiled binaries in MATLAB, or things that the JIT compiler handles well, the more realistic expectation is for MATLAB to be faster than the generated C code. The times when we see large speed-ups tend to correspond to those functions which are still implemented as complicated MATLAB functions in MATLAB. One might expect, therefore, to see speedups with QUADGK or QUAD2D, for example, but not with FFT.
With a simple script, we are really just comparing the C compiler to the MATLAB JIT compiler. For instance, the "mod" function is executing the exact same binary code in MATLAB as it is in a MEX file generated with MATLAB Coder. There just is not any opportunity for speedup here.