加速Matlab Engine调用

Dav*_*ave 6 c c++ performance matlab mixed-programming

我正在使用MATLAB Engine APIMATLAB与C/C++连接起来.

在我的特定情况下,MATLAB用于计算某些东西,结果用C打印.但是,在双方的各种测试中,我注意到C中的显着性能损失.

以下是MATLAB函数调用的示例:

tic;
data = predictIM(data);
toc;
Run Code Online (Sandbox Code Playgroud)

在C方面,我调用类似的函数如下:

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());
Run Code Online (Sandbox Code Playgroud)

我在C++中的计时器实现如下:

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);
      }
};
Run Code Online (Sandbox Code Playgroud)

上述MATLAB代码以大约每秒180帧的速度运行,包括设置矩阵(data),而C代码仅为24 FPS.我用tic/ toc来测量MATLAB中的执行时间,而我自己的定时器实现则用在C/C++端.

在分析应用程序时,我注意到MATLAB引擎调用是瓶颈.我知道Linux MATLAB Engine实现使用命名管道与MATLAB连接,我想知道是否有办法加速MATLAB与其引擎的通信?

her*_*tao 1

首先,这样衡量 MATLAB 引擎是不公平的。您应该只像在 MATLAB 中那样对计算时间进行计时,如下所示:

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()); 
Run Code Online (Sandbox Code Playgroud)

实际上,根据我的经验,运行 MATLAB 并用 C/C++ 调用其引擎应该具有相似的速度,因为它们实际上取决于 MATLAB 软件本身。

其次,我确实有一个关于可能的加速的建议。您应该在整个 C/C++ 项目中仅打开单个 MATLAB 引擎,而不是为每次调用创建一个引擎。像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我包括了将变量推入 Matlab 工作区的时间,因为它会显着减慢执行时间。在我的特定情况下,设置 3x16 矩阵需要 15 毫秒,而使用它并计算结果需要 28 毫秒。检索结果还需要 20 毫秒。因此,测量设置/获取矩阵的时间对于整体性能似乎很重要。在我的实现中,我只使用了一次 Matlab 引擎。 (2认同)