Skip to content

How to check memory usage at specified line of code on Android

A good software needs to save memory usage. To do this, we first need to find out where the most memory is being used.This post describes a method to check memory usage at any line of codes.

Commands

The following command of Android system can output the amount of memory currently used by your program.

dumpsys meminfo -a your_app_name | grep -E 'TOTAL PSS:|Native Heap:|Graphics:'

Base on this, we can examine memory usage anywhere in the code.

C++ codes

The following code implements a C++ function that prints the memory usage at specified code line. It can output both CPU and GPU memory usage on Android system.

char CMD[] = "dumpsys meminfo -a your_app_name | grep -E 'TOTAL PSS:|Native Heap:|Graphics:' ";

void printMemory()
{
    vector<int> vMem;
    char result[4096] = {0};

    vector<string> vString;
    FILE* fp = nullptr;
    if ((fp = popen(CMD, "r")) != nullptr){
        while(fgets(result, sizeof(result), fp)){
            vString = Split((char*)result, ":");
            int mem = 0;
            sscanf(vString[1].c_str(),"%d", &mem);
            vMem.push_back(mem);
        }
        pclose(fp);
    }

    if(V_MEM.size() == 3)  printf("Memory Usage At %-30s-> CPU:%06d GPU:%06d Total:%07d\n",lable, vMem[0],vMem[1],vMem[2]);
    return;
}

Call the “printMemory” function where you want to check memory.

Leave a Reply