Consider the following mex function written in C, which returns a column vector:
#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int x = *mxGetPr(prhs[0]); int length = *mxGetPr(prhs[1]); plhs[0] = mxCreateDoubleMatrix(x, 1, mxREAL); double *output_vector = mxGetPr(plhs[0]); int i; for(i = 0; i < length; ++i) { output_vector[i % x] += 1;
} }
If I compile this code in Matlab and then run the function with inputs (5, 1000000000), it takes 3.228 s. Consider now the following altered code:
#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int x = *mxGetPr(prhs[0]); int length = *mxGetPr(prhs[1]); plhs[0] = mxCreateDoubleMatrix(x, 1, mxREAL); //double *output_vector = mxGetPr(plhs[0]); double *output_vector = malloc(x*sizeof(double)); int i; for(i = 0; i < length; ++i) { output_vector[i] = 0.0; } for(i = 0; i < length; ++i) { output_vector[i % x] += 1; } free(output_vector); }
If I compile and run the function with the same inputs as before, it takes only 0.627 s.
It seems like editing elements of an mxArray is much slower than editing elements of a double array. It seems like there should be no issues with MATLABs column-major order vs the row-major order in C since I am only using a vector here.
Any ideas why I am seeing this time difference?
Here is some further information:
- OS: 64-bit Windows 10.
- Compiler: MinGW64 Compiler (C), with the additional compile flags -std=c99 and -pedantic.
- MATLAB version: R2016b
Update: For the simple example above, updating the mxArray takes about 5 times as long. In another code which I am using for an actual application, updating an mxArray instead of a double array takes 30 times as long.
Update 2: Please see my new timings in my comment below after incorporating the helpful suggestions by Walter and James. After fixing an error in the second code above, writing to an mxArray is now 10x slower than a double array for this simple example.
Best Answer