如何在Matlab

时间:2015-07-14 01:15:58

标签: c++ matlab dll loadlibrary dynamic-allocation

我编写了一个C ++接口DLL来调用英特尔集成性能基元(IPP)库中的一些关键图像处理统计测量方法,以便我们可以利用SIMD功能。我能够使用calllib

将两个2D Matlab数组传递到函数中
A = single( rand(3,4) );
B = single( rand(3,2) );

pOut = calllib('IPPInterface', 'myFunc', A' , B' , size(A,1), size(A,2) , size(B,1), size(B,2) );

在C ++中,myFunc具有以下签名和正文片段......

float* myFunc( float A[] , float B[] , int nRowsA , int nColsA , int nRowsB , int nColsB )
{
    ...
    float[] pDst = new float[nRowsA*nColsA];
    ...
    return pDst;
}

我不确定的是Matlab如何成功地从内存中删除这些缓冲区。它们最终以lib.pointers的形式出现在Matlab过程中:

>> class(pOut)

ans =

lib.pointer

我只是好奇我是在做什么是一个坏主意,或者如果调用Matlab的clear pOut会处理所有事情并避免可想象的内存泄漏。

1 个答案:

答案 0 :(得分:1)

所以我通过在Matlab中创建两个数组进行了一些内存测试,如下所示......

I = single( rand( 1200 , 1600 ) );
T = single( rand( 100  , 100  ) );

然后我将我的函数放在一个循环中,将内存使用情况打印到文本文件并清除返回的libpointer。

for i = 1:10000
    lp = calllib('IPPInterface', 'myFunc', I , T , size(I,2) , size(I,1) , size(T,2) , size(T,1) );
    clear lp;

    [u,s] = memory;

    fprintf( fileID ,'%13g    %13s\n' ,  u.MemUsedMATLAB , s.SystemMemory.Available );
end 

这条路线肯定会填满我的物理记忆,正如你在下面看到的那样,并且让我确信我所做的事情是一个坏主意,而且Matlab在一些自动化垃圾收集中并没有像你那样处理这个问题。

>> memory
Maximum possible array:              38799 MB (4.068e+010 bytes) *
Memory available for all arrays:     38799 MB (4.068e+010 bytes) *
Memory used by MATLAB:               21393 MB (2.243e+010 bytes)
Physical Memory (RAM):               34814 MB (3.650e+010 bytes)

*  Limited by System Memory (physical + swap file) available.
>> clear all
>> memory
Maximum possible array:              38803 MB (4.069e+010 bytes) *
Memory available for all arrays:     38803 MB (4.069e+010 bytes) *
Memory used by MATLAB:               21388 MB (2.243e+010 bytes)
Physical Memory (RAM):               34814 MB (3.650e+010 bytes)

*  Limited by System Memory (physical + swap file) available.
>> 

Matlab memory profile log data

Task Manager showing memory leak

如果我关闭Matlab而不是操作系统自然会回收所有内存。

Task Manager showing reclaimed memory as Matlab is closed

在Matlab的网站上挖掘之后,我确实找到了一个足够接近的示例,该示例在共享库中动态分配了一个c-struct,后来Matlab必须调用在同一个库中编写的函数唯一的任务是删除该结构。

Working with Pointer Arguments; Multilevel Pointers

这个例子是正确的,在实现对共享库的简单接口调用以取消分配我的数组并在完成后使用它

void deallocateArray( float* A )
{
    delete[] A;
}

内存配置文件是平的,整个10000次迭代完成得更快......

for i = 1:10000
    lp = calllib('IPPInterface', 'myFunc', I , T , size(I,2) , size(I,1) , size(T,2) , size(T,1) );
    calllib('IPPInterface', 'deallocateArray', lp );
    clear lp;

    [u,s] = memory;

    fprintf( fileID ,'%13g    %13s\n' ,  u.MemUsedMATLAB , s.SystemMemory.Available );
end 

enter image description here