How to free array memory when using Matlab mex?

[Old posts from the commercial version of ArrayFire] Discussion of ArrayFire using CUDA or OpenCL.

Moderator: pavanky

How to free array memory when using Matlab mex?

Postby DThoris » Thu Feb 20, 2014 7:56 am

Hi,

I've looked at other posts and I found the answer, but not the solution.
Below is a simple example:

Code: Select all
#include <mex.h>
#include <cuda.h>
#include <driver_types.h>
#include <cuda_runtime_api.h>
#include <arrayfire.h>

using namespace af;

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    size_t free = 0, total = 0;
    cudaError_t result = cudaMemGetInfo(&free, &total);

    mexPrintf("free memory %u MB, total memory  %u MB. ", free/1024/1024, total/1024/1024);

    if( total > 0 )
        mexPrintf("%2.2f%% free\n", (100.0*free)/total );
    else
        mexPrintf("\n");

    int N = 256;
    array dummy = constant(2.0,N,N,N);
    float *out = dummy.host<float>();                   // device to host
    array::free(out);
    dummy.unlock();

    cudaDeviceReset();
}


If arrayfire functions aren't called (comment 5 lines from int N) I get:
free memory 5312 MB, total memory 5375 MB. 98.82% free

If I run it as it is:
free memory 5189 MB, total memory 5375 MB. 96.53% free

The free memory reduces if I recompile the mex file.
What should I do to free all memory?

I am using the latest arrayfire with cuda 5.5 and matlab2012a.

Thanks for your help.
DThoris
 
Posts: 6
Joined: Thu Feb 20, 2014 7:42 am

Re: How to free array memory when using Matlab mex?

Postby pavanky » Thu Feb 20, 2014 4:16 pm

ArrayFire has a memory manager that frees memory when the application closes. This is done to reduce the memory allocation overhead and reuse already allocated memory.

You can check this by running the same code multiple times. You will notice no new memory is being allocated after the first run.
Pavan Yalamanchili,
ArrayFire
--
~ If it is not broken, you have not tried hard enough ~
User avatar
pavanky
Site Admin
 
Posts: 1123
Joined: Mon Mar 15, 2010 7:39 pm
Location: Atlanta, GA


Return to [archive-commercial] Programming & Development with ArrayFire

cron