Speeding up Matlab Engine calls

I interact with MATLAB with C / C ++ using the MATLAB Engine API .

In my particular case, MATLAB is used to calculate something, and the result is printed in C. However, in all the different tests on both sides, I noticed significant performance losses in C.

Here is an example of MATLAB function calls:

tic; data = predictIM(data); toc; 

On the C side, I call similar functions as follows:

 iMod::Timer_T<high_resolution_clock> t; engPutVariable(ep, "data", dataContent); engEvalString(ep, "[posture] = predictIM(data);"); UT_NOTIFY(LV_DEBUG,"The execution took "<<t.seconds()); 

My timer implementation in C ++ is as follows:

 template< class Clock > class Timer_T { typename Clock::time_point start; public: Timer_T() : start( Clock::now() ) {} typename Clock::duration elapsed() const { return Clock::now() - start; } double seconds() const { return elapsed().count() * ((double)Clock::period::num/Clock::period::den); } }; 

The above MATLAB code runs at about 180 frames per second, including setting the matrix ( data ), while the C code only 24 FPS. I used tic / toc to measure runtime in MATLAB, while my own timer implementation is used on the C / C ++ side.

While profiling the application, I noticed that calls to the MATLAB Engine are a bottleneck. I know that the Linux implementation of MATLAB Engine uses named pipes to interact with MATLAB, and I was wondering if there is a way to speed up the exchange of MATLAB with its Engine?

+6
source share
1 answer

First, it’s unfair to measure a MATLAB engine. You should only calculate the calculation time in the same way as in MATLAB, for example:

 engPutVariable(ep, "data", dataContent); // you should not time this iMod::Timer_T<high_resolution_clock> t; engEvalString(ep, "[posture] = predictIM(data);"); // time this only for fair UT_NOTIFY(LV_DEBUG,"The execution took "<<t.seconds()); 

In fact, in my experience, starting MATLAB and calling its engine in C / C ++ should have similar speed, since they actually depend on MATLAB software.

Secondly, I have advice for a possible speedup. You should open only one MATLAB engine in the entire C / C ++ project, instead of creating it for each call. Like this:

 int main() { // Open MATLAB engine for the whole project Engine *ep = engOpen(NULL); // Use it multiple times for (int i=0; i<100; ++i){ engEvalString(ep, ...); } // Close MATLAB engine engClose(ep); return 0; } 
+1
source

Source: https://habr.com/ru/post/976962/


All Articles