I am porting a game written in C++ to Android using NDK. I need to know how much memory it consumes while running. I am looking for programmatically way to find the memory usage of Android application written in C++.
Asked
Active
Viewed 5,583 times
5
-
one way is to override the `new` and `delete` operator and do some bookkeeping. – user1095108 Jun 14 '13 at 13:26
3 Answers
8
The two functions based on JonnyBoy's answer.
static long getNativeHeapAllocatedSize(JNIEnv *env)
{
jclass clazz = (*env)->FindClass(env, "android/os/Debug");
if (clazz)
{
jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "getNativeHeapAllocatedSize", "()J");
if (mid)
{
return (*env)->CallStaticLongMethod(env, clazz, mid);
}
}
return -1L;
}
static long getNativeHeapSize(JNIEnv *env)
{
jclass clazz = (*env)->FindClass(env, "android/os/Debug");
if (clazz)
{
jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "getNativeHeapSize", "()J");
if (mid)
{
return (*env)->CallStaticLongMethod(env, clazz, mid);
}
}
return -1L;
}

Wiz
- 2,145
- 18
- 15
-
5Actually these java methods are native methods themselves. According to http://androidxref.com/source/xref/frameworks/base/core/jni/android_os_Debug.cpp (the cpp-source) you could use `mallinfo()` and then read the values for `uordblks` (`getNativeHeapAllocatedSize()`) and `usmblks` (`getNativeHeapSize()`) – super-qua Apr 08 '15 at 09:43
-
5
In Java, you can check the native memory allocated/used with:
Debug.getNativeHeapAllocatedSize()
Debug.getNativeHeapSize()
See:
http://developer.android.com/reference/android/os/Debug.html#getNativeHeapAllocatedSize%28%29
http://developer.android.com/reference/android/os/Debug.html#getNativeHeapSize%28%29

JonnyBoy
- 1,555
- 14
- 24
1
Debug.getNativeHeapAllocatedSize()
andDebug.getNativeHeapSize()
return information about memory allocations performed by malloc()
and related functions only. You can easily parse /proc/self/statm
from C++ and get the VmRSS metric.

Dmitry Shesterkin
- 308
- 3
- 8