Android Settings中應用內存如何計算的

在 Android Settings中,“應用” - “正在運行”,可以看到內存相關的信息。如下圖

Android Settings中應用內存如何計算的

1.總內存,空閒內存

這三個內存指標都來自 /proc/meminfo 這支文件中。

<code>root@generic_x86:/proc # cat meminfo
MemTotal: 1551556 kB
MemFree: 1176792 kB
Buffers: 4620 kB
Cached: 157696 kB
/<code>

總內存 = Memtotal

剩餘內存 = MemFree + Cached - SECONDARY_SERVER_MEM

SECONDARY_SERVER_MEM 為 ActivityManger.Meminfo.secondaryServerThreshold

2.應用的內存

如上,Clock 的內存為 4.1 M。

這個內存值取自 Pss ,從 ActivityManagerService.getProcessesPss()中取得。​

<code>long[] pss = ActivityManagerNative.getDefault().getProcessPss(pids);
int bgIndex = 0;
for (int i=0; i<pids.length> ProcessItem proc = mAllProcessItems.get(i);
changed |= proc.updateSize(context, pss[i], mSequence);

boolean updateSize(Context context, long pss, int curSeq) {
mSize = pss * 1024;
if (mCurSeq == curSeq) {
String sizeStr = Formatter.formatShortFileSize(
context, mSize);
if (!sizeStr.equals(mSizeStr)){
mSizeStr = sizeStr;
// We update this on the second tick where we update just
// the text in the current items, so no need to say we
// changed here.
return false;
}
}
return false;
}

/<pids.length>/<code>

這個Pss 與 procrank 展示出來的 pss 是一樣的。所以說他們應該取的同一個值。繼續看看 ActivityManagerService 如何拿的。

<code>public long[] getProcessPss(int[] pids) {
4294 enforceNotIsolatedCaller("getProcessPss");
4295 long[] pss = new long[pids.length];
4296 for (int i=pids.length-1; i>=0; i--) {
4297 ProcessRecord proc;
4298 int oomAdj;
4299 synchronized (this) {
4300 synchronized (mPidsSelfLocked) {
4301 proc = mPidsSelfLocked.get(pids[i]);
4302 oomAdj = proc != null ? proc.setAdj : 0;
4303 }
4304 }
4305 long[] tmpUss = new long[1];
4306 pss[i] = Debug.getPss(pids[i], tmpUss);
4307 if (proc != null) {
4308 synchronized (this) {
4309 if (proc.thread != null && proc.setAdj == oomAdj) {
4310 // Record this for posterity if the process has been stable.
4311 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList);
4312 }
4313 }
4314 }
4315 }
4316 return pss;
4317 }
/<code>

pss[i] = Debug.getPss(pids[i], tmpUss);

Debug.getPss() 有兩個實現,帶參與不帶參。帶參的是獲取進程列表的內存。不帶參對應用可見,在應中,我們就可以用 Debug.getPss() 來獲取進程對標系統設置中的內存了。

對了,這個單位是 kb,實際計算的時候要注意了。


分享到:


相關文章: