How can I best utilize multi-core processors when calling the MATLAB 7.4 (R2007a) engine interface from C++?

1 view (last 30 days)
I would like to best utilize my multicore processor for computations when calling the MATLAB 7.4 (R2007a) engine interface from a C++ project.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
When using MATLAB 7.4 (R2007a) via the Engine interface, you can perform an "engEvalString" of the MATLAB command "feature('NumThreads',n)" to enable multithreaded computation and to set the number of computation threads to the integer "n".
If you run MATLAB on a multiple-CPU system (multiprocessor or multicore),
you can use multithreaded computation, which can improve performance for some
operations. MATLAB can take advantage of multithreading capabilities for element-wise numerical computations such as "sin" and "log", and BLAS (Basic Linear Algebra Subroutines) library computations such as matrix multiply.
The following C++ code demonstrates using the MATLAB 7.4 (R2007a) engine interface and enable multithreaded computation:
// matopen.cpp : Defines the entry point for the console application.
//#include <stdio.h>
#include <iostream>
#include "engine.h"
using namespace std;
class EngineOpen
{
public:
EngineOpen();
virtual ~EngineOpen();
int Command();
protected:
engine *ep;
};
EngineOpen::EngineOpen()
{
cout << "starting engine" << endl;
if( !(ep = engOpen("\0")) )
cout << "Unable to start MATLAB!" << endl;
else
cerr << "engine started" << endl;
}
EngineOpen::~EngineOpen()
{
engClose(ep);
}
int EngineOpen::Command()
{
//Set number of
engEvalString(ep, "feature('NumThreads',feature('NumCores'))");
//Evaluate a numerical expression
engEvalString(ep, "surf(rand(10,10))");
return -2;
}
int main(int argv, char** argc)
{
EngineOpen eng;
eng.Command();
}
You can build and run this example in MATLAB
mbuild -setup
And select a supported C++ compiler.
optsfile = [matlabroot '\bin\win32\mexopts\msvc80engmatopts.bat'];
mex('-f', optsfile, 'matopen.cpp' )
system(matopen.exe)
You can experiment by increasing the number of threads if you have a machine with more CPUs. Note that, because MATLAB code has some additional first-time running costs (due to JIT/accelerator code generation), it is recommended to run code at least twice when timing computations with tic/toc or other means.

More Answers (0)

Products


Release

R2007a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!