Here's a more detailed NDK answer:
Looking at the Bionic LibC source for sysconf reveals that _SC_PHYS_PAGES
and _SC_AVPHYS_PAGES
are implemented by reading /proc/meminfo
, which is maintained by the Linux kernel. The first few lines of that file on the Lenovo Android 7.0.1 device with 4GB RAM I'm using look like this:
MemTotal: 3721064 kB
MemFree: 208108 kB
MemAvailable: 2543032 kB
sysconf( _SC_PHYS_PAGES)
gives you the MemTotal
value, in units of the page size. This seems to be the total memory available to Android for code, data, and so on. It's about 300MB less than the claimed physical RAM on the device I'm using, which may be accounted for by the screen buffer and so on.
sysconf( _SC_AVPHYS_PAGES)
gives you the MemFree
value, in the same units. This appears to be the memory that isn't in use for anything at all. On my 4GB device, it's only about 200MB.
Sadly, there is no sysconf parameter for the far more useful MemAvailable
value, which is the RAM that can be made available if required. Apparently this is because MemAvailable
was only added to the Linux kernel in early 2014, while the sysconf() support seems rather older than that. MemAvailable
is not in a Samsung Android 5.0, but is in Amazon FireOS 5.6 (based on Android 5.1), and a Motorola Android 7.1; I don't know about 6.x.
What I'm planning to do for an NDK test harness (not a app that will be distributed), having got to the bottom of this, is use MemAvailable
if it is there, and otherwise use half the physical RAM size. Since I will have to read /proc/meminfo
to find out if MemAvailable
is there, there's no point in having Bionic LibC read it again if I call sysconf().