marcman
marcman

Reputation: 3391

Calling C/C++ Code as MEX File vs. Pure C/C++

I personally love high level programming languages. For proof-of-concept stuff, MATLAB is great. Plus you can easily visualize almost anything with MATLAB.

However, I often need to write C or C++ code for the sake of speed. Visualizations in C/C++ are a pain in the neck though. In an ideal world I want MATLAB visualization tools at C/C++ speeds. For me that implies I should MEX the necessary C/C++ functions and just call them from a MATLAB script, using MATLAB's tools to perform the visualizations. Ideally this gives me the best of both worlds. However, I don't want to end up with slow C/C++ run times as a result of calling the function via MEX files.

Do I sacrifice a the 10x-100x speed gains of C++ when calling C/C++ functions as compiled MEX functions? That is, does mexFunction(param1, param2) as called from a MATLAB script necessarily run slower than running the compiled binary?

Upvotes: 3

Views: 947

Answers (1)

Daniel
Daniel

Reputation: 36720

I think to answer this question you must think about what really causes the overhead. Each function call to mex itself causes an overhead and further passing the data to mex (to my experience only that direction, not passing back the result) also causes some overhead. I assume the primary reason is that M-Code is copy-on-write optimized which means my code never copied the input data, but the mex implementation does receive a copy. To give an example where mex behaved "bad", I think we all agree that C++ is faster iterating and that mathworks probably has qualified programmers, so why was I able to beat the performance implementing binary search in MATLAB?. In this case passing the data to the mex function simply made it slow. A lot of data was passed for which you had to pay the overhead and finally the data was barely touched (binary search).

Finally, how large is the overhead really? For a nop call, it is only 0.00001s, (No input, no output, no calculation). For passing data, I don't have any detailed benchmark, but from the binary search example I linked above it must be somewhere below 0.5s/GB.

Now do the math for your case and decide if it is worth switching to c++.

Upvotes: 1

Related Questions