如何分析使用 matlab 编辑器编写并使用 gcc 编译的 MEX 函数

How can I profile a MEX function written using the matlab editor and compiled using gcc

我想剖析我在 matlab (2021a) 编辑器中编写的 mex 函数。我现在能做的最好的就是使用 matlab 的 tic、toc 函数来测量总执行时间,但我不知道如何使用更详细的诊断工具来评估代码性能。我发现其他 questions and responses 使用 visual studio 讨论这个问题,但回复似乎使用旧版本的 visual studio 而不是我当前的 2019 版本。我也不是超级熟悉 visual studio,所以我不确定在哪里可以找到他们提到的一些工具,这些工具似乎已从以前版本中的位置移走。

我决定为此寻求两种解决方案。第一个是按照上面的评论 (whosebug.com/a/47888078/7328782) 中的建议将计时器添加到我的代码中。然后,您可以使用以下代码片段对脚本进行编程,将值输出到 matlab 控制台:

       std::ostringstream stream;
           stream << "Here is the name/value pair that you entered." << std::endl;
           displayOnMATLAB(stream);
           stream << SIG.rows() << " " << SIG.cols() << std::endl;
           displayOnMATLAB(stream);

并确保在 mexFunction 主体之外但仍在 mexFunction 的 class 定义内包括以下函数定义:

// outputting to matlab console for debugging
    void displayOnMATLAB(std::ostringstream& stream) {
        // Pass stream content to MATLAB fprintf function
        matlabPtr->feval(u"fprintf", 0,
            std::vector<matlab::data::Array>({ factory.createScalar(stream.str()) }));
        // Clear stream buffer
        stream.str("");
    }

但是,简单地对一段 C++ 代码计时并不一定能全面说明您可以使用代码优化的内容。例如,Microsoft visual studio 的分析工具(详细 introduction/overview/tutorials 在他们的论坛上包含 here) can tell you how much memory is being consumed at a given line, your processor usage throughout the script and much more. You might be explicitly looking to get a good idea of how neat and efficient a certain line is, or you might catch that an innocuous line could be running fast relative to your bottleneck but is actually consuming far more resources than it should. I decided to simply port my mex function code over to visual studio. Luckily, Matlab support has published a response,解释了如何执行此操作。到目前为止,它似乎适用于 2021a 和 Visual Studio 2019 年,尽管响应是针对 Matlab 和 Visual Studio.

的旧版本编写的

(注意,模块定义文件只需要你用我认为的项目名称替换MYFILE语句即可。其他两行保持原样)

更新

以上回答有一些问题需要解决。到目前为止,我发现的最佳选择是使用上面评论中提到的 Cris Luengo 的方法。