简体   繁体   English

MATLAB包装器中的MEX代码

[英]MEX code in a MATLAB Wrapper

I have the following code: 我有以下代码:

for i=1:N,
    some_mex_file();
end

My MEX file does the following: 我的MEX文件执行以下操作:

  1. Declares an object, of a class I defined, that has 2 large memory blocks, ie, 32x2048x2 of type double. 声明一个我定义的类的对象,该对象具有2个大内存块,即double类型的32x2048x2。
  2. Processes the data in this object. 处理此对象中的数据。
  3. Destroys the object. 销毁对象。

I am wondering if it takes more time when I call a MEX file in a loop that allocates large memory blocks for its object. 我想知道在为对象分配大内存块的循环中调用MEX文件时是否需要花费更多时间。 I was thinking of migrating to C++ so that I can declare the object only once and just reset its memory space so that it can be used again and again without new declaration. 我当时正在考虑迁移到C ++,以便我只能声明一次对象,而只是重置它的内存空间,这样就可以一次又一次地使用它而无需进行新的声明。 Is this going to make a difference or going to be a worthless effort? 这会有所作为还是徒劳? In other words, does it take more time to allocate a memory in MEX file than to declare it once and reuse it? 换句话说,在MEX文件中分配内存要比一次声明并重用它花费更多的时间吗?

So, the usual advice here applies: Profile your code (both in Matlab and using a C/C++ profiler) , or at least stop it in a debugger several times to see where it's spending its time. 因此,这里的一般建议适用: 对代码进行分析(在Matlab中并使用C / C ++探查器) ,或者至少在调试器中将其停止几次,以查看其花费的时间。 Stop "wondering" about where it's spending its time, and actually measure where it's spending its time. 停止“怀疑”它在哪里花费时间,并实际衡量它在哪里花费时间。

However, I have run into problems like this, where allocating/deallocating memory in the MEX function is the major performance sink. 但是,我遇到了这样的问题,在MEX函数中分配/取消分配内存是主要的性能接收器。 You should verify this, however, by profiling (or stopping the code in a debugger). 但是,您应该通过概要分析(或在调试器中停止代码)来验证这一点。

The easiest solution to this kind of performance problem is twofold: 解决这种性能问题的最简单方法是双重的:

  1. Move the loop into the MEX function. 将循环移至MEX功能。 Call the MEX function with an iteration count, and let your fast C/C++ code actually perform the loop. 使用迭代计数调用MEX函数,然后让您的快速C / C ++代码实际执行循环。 This eliminates the cost of calling from Matlab into your MEX function (which can be substantial for large N), and facilitates the second optimization: 这消除了从Matlab调用您的MEX函数的费用(这对于大N而言可能是相当大的),并且有助于进行第二次优化:

  2. Have your MEX function cache its allocation/deallocation, which is much, much easier (and safer) to do if you move the loop into the MEX function. 让您的MEX函数缓存其分配/取消分配,如果将循环移到MEX函数中,这将非常容易(安全得多)。 This can be done several ways, but the easiest is to just allocate the space once (outside the loop), and deallocate it once the loop is done. 这可以通过几种方法完成,但最简单的方法是只分配一次空间(在循环外部),并在循环完成后将其释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM