Investigating Your RAM Usage

1.In this document

  1. Interpreting Log Messages                 内存分析日志中各消息的含义
  2. Viewing Heap Updates                  查看当前内存快照的2种方法
  3. Tracking Allocations                      跟踪记录内存分配2种方法
  4. Viewing Overall Memory Allocations  用adb站在全局角度查看内存情况,及各行列的含义
  5. Capturing a Heap Dump                     捕获内存快照的3种方法
  6. Triggering Memory Leaks                   如何让程序暴漏内存泄漏的方法

  See Also

  Because Android is designed for mobile devices, you should always be careful about how much random-access memory (RAM) your app uses. Although Dalvik and ART perform routine garbage collection (GC), this doesn’t mean you can ignore when and where your app allocates and releases memory. In order to provide a stable user experience that allows the system to quickly switch between apps, it is important that your app does not needlessly consume memory when the user is not interacting with it.

尽管Dalvik 有gc,但是还要注意内存使用,当应用不再与用户交互时,就不应占有内存了。

  Even if you follow all the best practices for Managing Your App Memory during development (which you should), you still might leak objects or introduce other memory bugs. The only way to be certain your app is using as little memory as possible is to analyze your app’s memory usage with tools. This guide shows you how to do that.

时常用工具分析内存使用情况,可以保证应用使用较少的内存。

2.Interpreting Log Messages 内存分析日志中各消息的含义

  The simplest place to begin investigating your app’s memory usage is the runtime log messages. Sometimes when a GC occurs, a message is printed to logcat. The logcat output is also available in the Device Monitor or directly in an IDE such as Android Studio.

内存分析日志中各消息可以在LogCat中看到。

2.1 Dalvik Log Messages 内存分析日志之(1)dalvikvm类型日志

In Dalvik (but not ART), every GC prints the following information to logcat:

dalvikvm类型的日志格式如下:主要有4个部分
D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>

Example:

D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms
其中的含义如下:
GC Reason 如上例中的:  ” GC_CONCURRENT  “
  What triggered the GC and what kind of collection it is. Reasons that may appear include:
  触发GC的原因,它有下面几种

GC_CONCURRENT

A concurrent GC that frees up memory as your heap begins to fill up.

当应用堆开始满时,触发gc

GC_FOR_MALLOC

A GC caused because your app attempted to allocate memory when your heap was already full, so the system had to

stop your app and reclaim memory.

当应用堆已经满时,还要分配内存。

GC_HPROF_DUMP_HEAP

A GC that occurs when you request to create an HPROF file to analyze your heap.

创建 HPROF 文件时。

GC_EXPLICIT

An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed).

当代码中调用了gc() 时触发, 应避免直接调用。

GC_EXTERNAL_ALLOC

This happens only on API level 10 and lower (newer versions allocate everything in the Dalvik heap). A GC for externally

allocated memory (such as the pixel   data stored in native memory or NIO byte buffers).

api 10 以下才有可能出现的情况
Amount freed 上例中的  freed 2049K
 被gc回收的内存总量,
  The amount of memory reclaimed from this GC.
Heap stats * 上例中的 65% free 3571K/9991K
 释放的比例和对象大小/堆总量,如果这个数持续增加,说明有内存泄漏。
  Percentage free of the heap and (number of live objects)/(total heap size).
External memory stats 上例中的 external 4703K/5261K
 在外部申请的内存,api10以下才出现。
  Externally allocated memory on API level 10 and lower (amount of allocated memory) / (limit at which collection will occur).
Pause time 上例中的 paused 2ms+2ms
 释放所用的时间
  Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at the beginning of the collection and another near the end.
  As these log messages accumulate, look out for increases in the heap stats (the 3571K/9991K value in the above example). If this value continues to increase, you may have a memory leak.
 注意其中 的  heap stats the 3571K/9991K, 如果该值持续增加,表明有内存泄漏。

2.2 ART Log Messages 内存分析日志之(2)ART型日志

  Unlike Dalvik, ART doesn't log messages for GCs that were not explicitly requested. GCs are only printed when they are  they are deemed slow. More precisely, if the GC pause exceeds than 5ms or the GC duration exceeds 100ms. If the app is not in a pause perceptible process state, then none of its GCs are deemed slow. Explicit GCs are always logged.

ART只在有必要时才在logcat中打印日志,如:gc停顿5ms以上,或运行超过100ms。如果进程还是在不可见态,gc不会认为运行变慢了。

ART includes the following information in its garbage collection log messages:

art型日志的格式如下:
I/art: <GC_Reason> <GC_Name> <Objects_freed>(<Size_freed>) AllocSpace Objects, <Large_objects_freed>(<Large_object_size_freed>) <Heap_stats> LOS objects, <Pause_time(s)>

Example:

I/art : Explicit concurrent mark sweep GC freed 104710(7MB) AllocSpace objects, 21(416KB) LOS objects, 33% free, 25MB/38MB, paused 1.230ms total 67.216ms
GC Reason 如上例中: I/art : Explicit
  触发GC的原因,它有下面几种:
  What triggered the GC and what kind of collection it is. Reasons that may appear include:

Concurrent

A concurrent GC which does not suspend app threads. This GC runs in a background thread and does not prevent allocations.

另一个在其它后台线程中的gc被触发,它不阻止清理本线程的内存。

Alloc

The GC was initiated because your app attempted to allocate memory when your heap was already full. In this case,

the garbage collection occurred in the allocating thread.

当应用的堆已満时,在线程中申请内存时,这个gc被触发。

Explicit

The garbage collection was explicitly requested by an app, for instance, by calling gc() or gc().

As with Dalvik, in ART it is recommended that you trust the GC and avoid requesting explicit GCs if possible.

Explicit GCs are discouraged since they block the allocating thread and unnecessarily was CPU cycles.

Explicit GCs could also cause jank if they cause other threads to get preempted.

这个是由直接调用gc()或gc().触发,art建议不要直接调用gc(),

NativeAlloc

The collection was caused by native memory pressure from native allocations such as Bitmaps or RenderScript allocation objects.

本地语言(如c/c++)写的代码中内存有压力时触发。

CollectorTransition

The collection was caused by a heap transition; this is caused by switching the GC at run time.

Collector transitions consist of copying all the objects from a free-list backed space to a bump pointer

space (or visa versa). Currently collector transitions only occur when an app changes process states

from a pause perceptible state to a non pause perceptible state (or visa versa) on low RAM devices.

运行时gc切换后触发,具体是在内存较低的设备上,一个进程从可见状态到不可见状态切换时。

HomogeneousSpaceCompact

Homogeneous space compaction is free-list space to free-list space compaction which usually occurs

when an app is moved to a pause imperceptible process state. The main reasons for doing this are

reducing RAM usage and defragmenting the heap.

当系统整理内存碎片时触发。

DisableMovingGc

This is not a real GC reason, but a note that collection was blocked due to use of GetPrimitiveArrayCritical.

while concurrent heap compaction is occuring. In general, the use of GetPrimitiveArrayCritical is strongly

discouraged due to its restrictions on moving collectors.

不是一个真正的gc清理,而是一个通知,当系统正在内存压缩内存,调用GetPrimitiveArrayCritical被阻止时,
通常GetPrimitiveArrayCritical失败是由于移动gc的限制。

HeapTrim

This is not a GC reason, but a note that collection was blocked until a heap trim finished.

不是一个真正的gc清理,裁剪堆过程中gc不可以回收,它被阻止时收到的通知。
GC Name 如上例中:  concurrent mark sweep GC
  ART has various different GCs which can get run.
ART 里有多个gc,它们如下:
Concurrent mark sweep (CMS)

A whole heap collector which frees collects all spaces other than the image space.

一个较完整的gc,除了镜像空间,都能清理。
Concurrent partial mark sweep A mostly whole heap collector which collects all spaces other than the image and zygote spaces.

除镜像空间和zygote空间,都可清理的gc。
Concurrent sticky mark sweep

A generational collector which can only free objects allocated since the last GC.

This garbage collection is run more often than a full or partial mark sweep since it is faster and has lower pauses.

这个gc比前两个常用,它运行更快同时有较少的停顿。
Marksweep + semispace A non concurrent, copying GC used for heap transitions as well as homogeneous space compaction (to defragement the heap).

压缩堆时使用的副本gc。
Objects freed 上例中: 104710(7MB) AllocSpace objects  中的104710
  The number of objects which were reclaimed from this GC from the non large object space.
本次gc回收的AllocSpace objects 的数目
Size freed 上例中: 104710(7MB) AllocSpace objects  中的7MB
  The number of bytes which were reclaimed from this GC from the non large object space.
本次gc回收的Los objects大小
Large objects freed  上例中的: 21(416KB) LOS objects 中的21
  The number of object in the large object space which were reclaimed from this garbage collection.
本次gc回收的大对象的数目。
Large object size freed 上例中的: 21(416KB) LOS objects 中的416KB
  The number of bytes in the large object space which were reclaimed from this garbage collection.
本次gc回收的大对象的字节大小。
Heap stats 上例中的  33% free, 25MB/38MB
  Percentage free and (number of live objects)/(total heap size).
回收所占比例 , 活动对象的大小/堆总计大小
Pause times 上例中的 paused 1.230ms total 67.216ms
  In general pause times are proportional to the number of object references which were modified while the GC was running. Currently, the ART CMS GCs only has one pause, near the end of the GC. The moving GCs have a long pause which lasts for the majority of the GC duration.
检查内存泄漏的一个方法:
  If you are seeing a large amount of GCs in logcat, look for increases in the heap stats (the 25MB/38MB value in the above example). If this value continues to increase and doesn't ever seem to get smaller, you could have a memory leak. Alternatively, if you are seeing GC which are for the reason "Alloc", then you are already operating near your heap capacity and can expect OOM exceptions in the near future.
在ART类型的日志中,有两条信息说明有内存泄漏:
1,注意上例中的 25MB/38MB 如果这个值持续增加且不减少,说明有内存泄漏。
2,当触发gc的原因是 Alloc 时。

3.Viewing Heap Updates 查看当前内存快照的2种方法

  To get a little information about what kind of memory your app is using and when, you can view real-time updates to your app's heap in Android Studio's HPROF viewer or in the Device Monitor:

可以在android studio中查看当前app的内存,cpu,gpu,网络使用情况,并进行分析。

3.1 Memory Monitor in Android Studio 查看当前内存快照方法(1):用AS

  Use Android Studio to view your app's memory use:

监查内存的步骤如下:
  1. Start your app on a connected device or emulator.
  2. Open the Android run-time window, and view the free and allocated memory in the Memory Monitor.
  3. Click the Dump Java Heap icon () in the Memory Monitor toolbar.

     Android Studio creates the heap snapshot file with the filename Snapshot-yyyy.mm.dd-hh.mm.ss.hprof in the Captures tab.

    按 Dump Java Heap 图标
  4. Double-click the heap snapshot file to open the HPROF viewer.

    Note: To convert a heap dump to standard HPROF format in Android Studio, right-click a heap snapshot in the Captures view and select Export to standard .hprof.

    在HPROF中查看快照,Captures tab页面中可以把as生成的.hprof转成mat可打开的标准 .hprof
  5. Interact with your app and click the () icon to cause heap allocation.
    按 Initiate GC 图标。
  6. Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.
    看哪里用内存多,然后调整。

3.2 Device Monitor 观察内存快照方法(2):用 device monitor

  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the Debug Monitor window, select your app's process from the list on the left.
  3. Click Update Heap above the process list.
  4. In the right-side panel, select the Heap tab.

The Heap view shows some basic stats about your heap memory usage, updated after every GC. To see the first update, click the Cause GC button.

      Figure 1. The Device Monitor tool, showing the [1] Update Heap and [2] Cause GC buttons. The Heap tab on the right shows the heap results.

Continue interacting with your app to watch your heap allocation update with each garbage collection. This can help you identify which actions in your app are likely causing too much allocation and where you should try to reduce allocations and release resources.

4.Tracking Allocations 跟踪记录内存分配的2种方法

  As you start narrowing down memory issues, you should also use the Allocation Tracker to get a better understanding of where your memory-hogging objects are allocated. The Allocation Tracker can be useful not only for looking at specific uses of memory, but also to analyze critical code paths in an app such as scrolling.

跟踪记录内存使用记录是个好习惯,它可以知道哪些对象占用了大量内存,也可分析哪些代码有危险。

  For example, tracking allocations when flinging a list in your app allows you to see all the allocations that need to be done for that behavior, what thread they are on, and where they came from. This is extremely valuable for tightening up these paths to reduce the work they need and improve the overall smoothness of the UI.

  To use the Allocation Tracker, open the Memory Monitor in Android Studio and click the Allocation Tracker icon. You can also track allocations in the Android Device Monitor:

4.1 Android Studio 跟踪记录内存分配方法(1):用AS

To use the Allocation Tracker in Android Studio:

 用AS跟踪内存使用情况的步骤:
  1. Start your app on a connected device or emulator
  2. Open the Android run-tme window, and view the free and allocated memory in the Memory Monitor.
  3. Click the Allocation Tracker icon () in the Memory Monitor tool bar to start and stop memory allocations.

     Android Studio creates the allocation file with the filename Allocations-yyyy.mm.dd-hh.mm.ss.alloc in the Captures tab.

    按 Allocation Tracker 图标
  4. Double-click the allocation file to open the Allocation viewer.
  5. Identify which actions in your app are likely causing too much allocation and determine where in your app you should try to reduce allocations and release resources.
    看哪里占内存多,然后调整。

4.2 Device Monitor 跟踪记录内存分配方法(2):用device monitor

 使用device monitor的步骤:
  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the DDMS window, select your app's process in the left-side panel.
  3. In the right-side panel, select the Allocation Tracker tab.
  4. Click Start Tracking.
    按 Start Tracking 按钮
  5. Interact with your app to execute the code paths you want to analyze.
  6. Click Get Allocations every time you want to update the list of allocations.
    按Get Allocations 按钮

  The list shows all recent allocations, currently limited by a 512-entry ring buffer. Click on a line to see the stack trace that led to the allocation. The trace shows you not only what type of object was allocated, but also in which thread, in which class, in which file and at which line.

              Figure 2. The Device Monitor tool, showing recent app allocations and stack traces in the Allocation Tracker.

Note: You will always see some allocations from DdmVmInternal and elsewhere that come from the allocation tracker itself.

 注意 device monitor 本身也会有一些内存分配,还要把它们当作你的应用分配的

  Although it's not necessary (nor possible) to remove all allocations from your performance critical code paths, the allocation tracker can help you identify important issues in your code. For instance, some apps might create a new Paint object on every draw. Moving that object into a global member is a simple fix that helps improve performance.

5.Viewing Overall Memory Allocations 用adb全局查看内存使用情况

5.1 命令

  For further analysis, you may want to observe how your app's memory is divided between different types of RAM allocation with the following adb command:

adb shell dumpsys meminfo <package_name|pid> [-d]

The -d flag prints more info related to Dalvik and ART memory usage.

The output lists all of your app's current allocations, measured in kilobytes.

When inspecting this information, you should be familiar with the following types of allocation:

用上述命令打印的结果,你应注意下面这两个类型的分配。
Private (Clean and Dirty) RAM
  This is memory that is being used by only your process. This is the bulk of the RAM that the system can reclaim when your app’s process is destroyed. Generally, the most important portion of this is “private dirty” RAM, which is the most expensive because it is used by only your process and its contents exist only in RAM so can’t be paged to storage (because Android does not use swap). All Dalvik and native heap allocations you make will be private dirty RAM; Dalvik and native allocations you share with the Zygote process are shared dirty RAM.
Private Clean和Private Dirty 是你的应用进程产生的内存,其中private dirty是运行时产生的无用内存。注意:所有的Dalvik与本地的分配都产生private dirty ram.应用进程与Zygote共享的内存是 shared dirty ram.
Proportional Set Size (PSS)
  This is a measurement of your app’s RAM use that takes into account sharing pages across processes. Any RAM pages that are unique to your process directly contribute to its PSS value, while pages that are shared with other processes contribute to the PSS value only in proportion to the amount of sharing. For example, a page that is shared between two processes will contribute half of its size to the PSS of each process.
  A nice characteristic of the PSS measurement is that you can add up the PSS across all processes to determine the actual memory being used by all processes. This means PSS is a good measure for the actual RAM weight of a process and for comparison against the RAM use of other processes and the total available RAM.
  
  For example, below is the the output for Map’s process on a Nexus 5 device. There is a lot of information here, but key points for discussion are listed below.
下面是一个adb shell dumsys meminfo xxx 示例
adb shell dumpsys meminfo com.google.android.apps.maps -d

Note: The information you see may vary slightly from what is shown here, as some details of the output differ across platform versions.

** MEMINFO in pid 18227 [com.google.android.apps.maps] **
Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 10468 10408 0 0 20480 14462 6017
Dalvik Heap 34340 33816 0 0 62436 53883 8553
Dalvik Other 972 972 0 0
Stack 1144 1144 0 0
Gfx dev 35300 35300 0 0
Other dev 5 0 4 0
.so mmap 1943 504 188 0
.apk mmap 598 0 136 0
.ttf mmap 134 0 68 0
.dex mmap 3908 0 3904 0
.oat mmap 1344 0 56 0
.art mmap 2037 1784 28 0
Other mmap 30 4 0 0
EGL mtrack 73072 73072 0 0
GL mtrack 51044 51044 0 0
Unknown 185 184 0 0
TOTAL 216524 208232 4384 0 82916 68345 14570 Dalvik Details
.Heap 6568 6568 0 0
.LOS 24771 24404 0 0
.GC 500 500 0 0
.JITCache 428 428 0 0
.Zygote 1093 936 0 0
.NonMoving 1908 1908 0 0
.IndirectRef 44 44 0 0 Objects
Views: 90 ViewRootImpl: 1
AppContexts: 4 Activities: 1
Assets: 2 AssetManagers: 2
Local Binders: 21 Proxy Binders: 28
Parcel memory: 18 Parcel count: 74
Death Recipients: 2 OpenSSL Sockets: 2

  Here is an older dumpsys on Dalvik of the gmail app:

** MEMINFO in pid 9953 [com.google.android.gm] **
Pss Pss Shared Private Shared Private Heap Heap Heap
Total Clean Dirty Dirty Clean Clean Size Alloc Free
------ ------ ------ ------ ------ ------ ------ ------ ------
Native Heap 0 0 0 0 0 0 7800 7637(6) 126
Dalvik Heap 5110(3) 0 4136 4988(3) 0 0 9168 8958(6) 210
Dalvik Other 2850 0 2684 2772 0 0
Stack 36 0 8 36 0 0
Cursor 136 0 0 136 0 0
Ashmem 12 0 28 0 0 0
Other dev 380 0 24 376 0 4
.so mmap 5443(5) 1996 2584 2664(5) 5788 1996(5)
.apk mmap 235 32 0 0 1252 32
.ttf mmap 36 12 0 0 88 12
.dex mmap 3019(5) 2148 0 0 8936 2148(5)
Other mmap 107 0 8 8 324 68
Unknown 6994(4) 0 252 6992(4) 0 0
TOTAL 24358(1) 4188 9724 17972(2)16388 4260(2)16968 16595 336 Objects
Views: 426 ViewRootImpl: 3(8)
AppContexts: 6(7) Activities: 2(7)
Assets: 2 AssetManagers: 2
Local Binders: 64 Proxy Binders: 34
Death Recipients: 0
OpenSSL Sockets: 1 SQL
MEMORY_USED: 1739
PAGECACHE_OVERFLOW: 1164 MALLOC_SIZE: 62

  Generally, you should be concerned with only the Pss Total and Private Dirty columns. In some cases, the Private Clean and Heap Alloc columns also offer interesting data. Here is some more information about the different memory allocations (the rows) you should observe:

在看adb shell dumpsys meminfo打印结果时,应注意 Pss Total,Private Dirty, Private Clean,Heap Alloc这几个列。

5.2 meminfo每行的含义

Dalvik Heap

The RAM used by Dalvik allocations in your app. The Pss Total includes all Zygote allocations (weighted by their sharing across

processes,as described in the PSS definition above).The Private Dirty number is the actual RAM committed to only your

app’s heap,composed of your own allocations and any Zygote allocation pages that have been modified since forking your app’s

process from Zygote.

Dalvik 使用的内存大小:其中
Pss Total 列是Zygote分配的内存大小(含共享部分)
Private Dirty 列是应用进程分配的内存和从zygote生成进程时带过来的内存。

Note: On newer platform versions that have the Dalvik Other section, the Pss Total and Private Dirty numbers for

Dalvik Heap do not include Dalvik overhead such as the just-in-time compilation (JIT) and GC bookkeeping, whereas older versions

list it all combined under Dalvik.

注意:在新版本中还有 Dalvik Other这行。

The Heap Alloc is the amount of memory that the Dalvik and native heap allocators keep track

of for your app.This value is larger than Pss Total and Private Dirty because your process was forked from Zygote and it

includes allocations that your process shares with all the others.

Heap Alloc列是应用进程 Dalvik和本地堆的内存记录。
.so mmap and .dex mmap

The RAM being used for mapped .so (native) and .dex (Dalvik or ART) code. The Pss Total number includes platform code

shared across apps;the Private Clean is your app’s own code. Generally, the actual mapped size will be much larger—the

RAM here is only what currently needs to be in RAM for code that has been executed by the app. However, the .so mmap has

a large private dirty, which is due to fix-ups to the native code when it was loaded into its final address.

已经映射的.so和.dex内存大小,其中:
Pass Total包含共享部分,
Private Clean 只是应用进程部分.
.oat mmap

This is the amount of RAM used by the code image which is based off of the preloaded classes which are commonly used by

multiple apps. This image is shared across all apps and is unaffected by particular apps.

多个app之间共享的 预映射的class 代码镜像大小。
.art mmap

This is the amount of RAM used by the heap image which is based off of the preloaded classes which are commonly used by

multiple apps.This image is shared across all apps and is unaffected by particular apps. Even though the ART image contains

Object instances,it does not count towards your heap size.

多个app之间共享的 预映射的class 堆镜像大小。这个镜像是很多应用共享。
.Heap (only with -d flag)

This is the amount of heap memory for your app. This excludes objects in the image and large object spaces,

but includes the zygote space and non-moving space.

命令中加入 -d 后才能显示。应用的堆大小。包含zygote空间和不静态空间,但是不含镜像和大对象空间。
.LOS (only with -d flag)

This is the amount of RAM used by the ART large object space. This includes zygote large objects.

Large objects are all primitive array allocations larger than 12KB.

ART大对象空间,包含zygote大对象,大对象一般大于12kb.
.GC (only with -d flag) This is the amount of internal GC accounting overhead for your app. There is not really any way to reduce this overhead.

应用内部记录的gc减少的数量。
.JITCache (only with -d flag)

This is the amount of memory used by the JIT data and code caches. Typically, this is zero since all of the apps will be

compiled at installed time.

JIT 数据和代码缓存大小。
.Zygote (only with -d flag)

This is the amount of memory used by the zygote space. The zygote space is created during device startup and is never

allocated into.

这里系统启动时占用的zygote的大小,它是固定的。
.NonMoving (only with -d flag)

This is the amount of RAM used by the ART non-moving space. The non-moving space contains special non-movable

objects such as fields and methods.You can reduce this section by using fewer fields and methods in your app.

ART使用的静态空间大小,里面是静态变量或静态方法。可以在代码中减小它们。
.IndirectRef (only with -d flag)

This is the amount of RAM used by the ART indirect reference tables. Usually this amount is small, but if it is too high,

it may be possible to reduce it by reducing the number of local and global JNI references used.

ART间接引用的空间大小,它很重要,可以通过减小本地或全局jni引用。
Unknown

Any RAM pages that the system could not classify into one of the other more specific items. Currently, this contains mostly

native allocations,which cannot be identified by the tool when collecting this data due to Address Space Layout

Randomization (ASLR). As with the Dalvik heap, the Pss Total for Unknown takes into account sharing with Zygote,

and Private Dirty is unknown RAM dedicated to only your app.

系统不能归类的RAM页,通常里面包含由于地址布局不规则(Adress Space Layout Randomization)
导致无法回收的本地分配。其中: Pss Total 是未知的共享zygote大小

 Private Dirty 是应用进程中未知的分配。

TOTAL

The total Proportional Set Size (PSS) RAM used by your process. This is the sum of all PSS fields above it. It indicates the

overall memory weight of your process,which can be directly compared with other processes and the total available RAM.

The Private Dirty and Private Clean are the total allocations within your process, which are not shared with other

processes.Together (especially Private Dirty), this is the amount of RAM that will be released back to the system

when your process is destroyed.Dirty RAM is pages that have been modified and so must stay committed to RAM

(because there is no swap); clean RAM is pages that have been mapped from a persistent file (such as code being executed)

and so can be paged out if not used for a while.

应用进程总内存开销,其中:
Private Dirty 和 Private Clean是进程自己分配的大小。
Dirty在进程结束后被回收。
Clean 是应用进程映射的page 对应的文件大小。
ViewRootImpl

The number of root views that are active in your process. Each root view is associated with a window, so this can help

you identify memory leaks involving dialogs or other windows.

应用进程中 root views 占的空间大小.每个view可能包含一个窗口。
AppContexts and Activities

The number of app Context and Activity objects that currently live in your process. This can be useful to quickly

identify leaked Activity objects that can’t be garbage collected due to static references on them, which is common.

These objects often have a lot of other allocations associated with them and so are a good way to track large memory leaks.

应用进程中活动的 Context和Activity 占空间大小。可以通过它快速识别没被回收的对象,
它们通常是由于静态引用。

Note: A View or Drawable object also holds a reference to the Activity that it's from, so holding a View or Drawable object can also lead to your app leaking an Activity.

注意:
View 或 Drawable都产生对Activity的引用,它们可能导致内存泄漏。

6.Capturing a Heap Dump 捕获内存快照的3种方法

  A heap dump is a snapshot of all the objects in your app's heap, stored in a binary format called HPROF. Your app's heap dump provides information about the overall state of your app's heap so you can track down problems you might have identified while viewing heap updates.

内存使用堆记录了内存堆中对象快照,可能通过它分析出哪里出了问题。

方法(1)使用AS

  To retrieve your heap dump from within Android Studio, use the Memory Monitor and HPROF viewer.

方法(2)使用 device monitor

  You can also still perform these procedures in the Android monitor:

  1. Open the Device Monitor.

    From your <sdk>/tools/ directory, launch the monitor tool.

  2. In the DDMS window, select your app's process in the left-side panel.
  3. Click Dump HPROF file, shown in figure 3.
  4. In the window that appears, name your HPROF file, select the save location, then click Save.

            Figure 3. The Device Monitor tool, showing the [1] Dump HPROF file button.

方法(2)在代码中使用 dumpHprofData()方法 

  If you need to be more precise about when the dump is created, you can also create a heap dump at the critical point in your app code by calling dumpHprofData().

  The heap dump is provided in a format that's similar to, but not identical to one from the Java HPROF tool. The major difference in an Android heap dump is due to the fact that there are a large number of allocations in the Zygote process. But because the Zygote allocations are shared across all app processes, they don’t matter very much to your own heap analysis.

  To analyze your heap dump, you can use Memory Monitor in Android Studio. You can also use a standard tool like jhat. However, first you'll need to convert the HPROF file from Android's format to the J2SE HPROF format. You can do this using the hprof-conv tool provided in the <sdk>/platform-tools/ directory. Simply run the hprof-conv command with two arguments: the original HPROF file and the location to write the converted HPROF file. For example:


android 下生成的.hprof与标准的.hprof格式不同,它包含了zygote进程的分配信息。
可以在AS中直接把它转换,也可以用命令行工具转换。下面就是命令行转换示例:
hprof-conv heap-original.hprof heap-converted.hprof

  You can now load the converted file into a heap analysis tool that understands the J2SE HPROF format.

When analyzing your heap, you should look for memory leaks caused by:

从.hprof分析内存时应注意内存泄漏,通常由于下面几个原因:
  • Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold a reference to the container Activity or Context.

    长期存在的Activity,Context,View,Drawable,它们可能由于其它对象引用而导致的。
  • Non-static inner classes (such as a Runnable, which can hold the Activity instance).
    非静态内部类,它可导致Activity实例长期存在。
  • Caches that hold objects longer than necessary.
    缓存可能长期引用一个对象。

7.Triggering Memory Leaks 如何让程序暴漏内存泄漏的方法

  While using the tools described above, you should aggressively stress your app code and try forcing memory leaks. One way to provoke memory leaks in your app is to let it run for a while before inspecting the heap. Leaks will trickle up to the top of the allocations in the heap. However, the smaller the leak, the longer you need to run the app in order to see it.

当上述工具分析内存时,应积极检查内存泄漏,通常把程序运行到某一个模块后呆一会,大的内存泄漏会慢慢地在堆顶,小的内存漏泄可能需要的时间多些。

  You can also trigger a memory leak in one of the following ways:

下面这两个方法可以加快让程序出现内存泄漏
  1. Rotate the device from portrait to landscape and back again multiple times while in different activity states. Rotating the device can often cause an app to leak an ActivityContext, or View object because the system recreates the Activity and if your app holds a reference to one of those objects somewhere else, the system can't garbage collect it.

    旋转activity
  2. Switch between your app and another app while in different activity states (navigate to the Home screen, then return to your app).
    在不同的activity或应用间切换,切到home,再切回到你的应用。

  Tip: You can also perform the above steps by using the "monkey" test framework. For more information on running the monkey test framework, read the monkeyrunner documentation.

也可以使用 monkey 这个 开源库检查内存泄漏。monkeyrunner

Android内存管理(5)*官方教程:Logcat内存日志各字段含义,查看当前内存快照,跟踪记录内存分配,用adb查看内存情况时各行列的含义,捕获内存快照的3种方法,如何让程序暴漏内存泄漏的方法的更多相关文章

  1. Android中的五大布局和logcat打印日志

    在android中的布局有五大类,有的时候你可能用到一种,但有的时候你也可能需要两种或者三种布局同时一起使用.这五种布局为别为:LinearLayout(线性布局),FrameLayout(框架布局) ...

  2. 后台跑包方法 断开ssh程序也能继续执行的方法screen命令

    aircrack-ng -w 字典路径 握手包路径 screen -S 001创建会话 screen -ls  列出窗口列表 screen -r 5位数字  进入会话指令 如果会话恢复不了,则是有可能 ...

  3. Python 源码剖析(六)【内存管理机制】

    六.内存管理机制 1.内存管理架构 2.小块空间的内存池 3.循环引用的垃圾收集 4.python中的垃圾收集 1.内存管理架构 Python内存管理机制有两套实现,由编译符号PYMALLOC_DEB ...

  4. iPhone/Mac Objective-C内存管理教程和原理剖析

    http://www.cocoachina.com/bbs/read.php?tid-15963.html 版权声明 此文版权归作者Vince Yuan (vince.yuan#gmail.com)所 ...

  5. 【Bugly干货分享】iOS内存管理:从MRC到ARC实践

    Bugly 技术干货系列内容主要涉及移动开发方向,是由Bugly邀请腾讯内部各位技术大咖,通过日常工作经验的总结以及感悟撰写而成,内容均属原创,转载请标明出处. 对于iOS程序员来说,内存管理是入门的 ...

  6. Objective C 内存管理[转]

    1  配对原则 alloc – release new – release retain - release copy – release 2  new和alloc-init的区别 (1)区别只在于a ...

  7. Objective-C内存管理与原理

    尽管苹果在 iOS 5/ Mac OS X 10.7 开始导入ARC,利用 Xcode4.2 可以使用该机能.ARC就是自动引用计数,是一项为Objective - C程序在编译时提供自动内存管理的功 ...

  8. FreeRTOS 动态内存管理

    以下转载自安富莱电子: http://forum.armfly.com/forum.php 本章节为大家讲解 FreeRTOS 动态内存管理,动态内存管理是 FreeRTOS 非常重要的一项功能,前面 ...

  9. IOS 非ARC开发内存管理的几条规则

    关于ios内存管理.在开发过程中,内存管理很重要,我简单说明一下. 1.正确用法 UIView *v = [[UIView alloc] init]; //分配后引用计数为1 [self.view a ...

随机推荐

  1. hdu 4005 The war

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4005 In the war, the intelligence about the enemy is ...

  2. 【BZOJ】【3164】【HEOI2013】Eden的博弈问题

    树形DP 这题在考场上直接写的TreeDP……当时也没想出一个像样的暴力来对拍……好像只能这么直接做了……? 都说是博弈树了,转移关系都给的这么直接了……也没啥难度了吧= =(怪不得大家都不愿意写题解 ...

  3. 【BZOJ】【3171】【TJOI2013】循环格

    网络流/费用流 最后能走回出发点……说明全部是环= = 而二分图上的环说明什么呢……完备匹配 对于每个点,它都有四个可能的匹配点,且已知它已经(伪)匹配的一个点,那么我们于已知每条(伪)匹配边,我们连 ...

  4. HTML5 canvas 绘图步骤

    1.先把canvas选出来,不选出来你往哪儿画! var oCan=  document.getElementById('xxx'); 2.声明基于 canvas 的context对象,没他你怎么调用 ...

  5. HDU 1465 不容易系列之一(错排,递归)

    简而言之,就是把n个信封全部装错的可能数.(中问题,具体看题目) //当n个编号元素放在n个编号位置,元素编号与位置编号各不对应的方法数用M(n)表示, //那么M(n-1)就表示n-1个编号元素放在 ...

  6. SQL技术内幕-4 row_number() over( partition by XX order by XX)的用法(区别于group by 和order by)

    partition by关键字是分析性函数的一部分,它和聚合函数不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录,partition by用于给结果集分组,如果没有指 ...

  7. 2016PHP开发者大会

    大会干货: Rasmus Lerdorf——<Speeding up the Web with PHP 7> PHP 7 is here. It brings drastic perfor ...

  8. LINUX进程控制

    1. 引言 一个程序是存储在文件中的机器指令序列.一般它是由编译器将源代码编译成二进制格式的代码.运行一个程序意味着将这个机器指令序列载入内存然后让处理器(cpu)逐条执行这些指令. 在Unix术语中 ...

  9. Jmeter 快速入门教程(三-3) -- 使用参数化

    参数化:简单的来理解一下,我们录制了一个脚本,这个脚本中有登录操作,需要输入用户名和密码,假如系统不允许相同的用户名和密码同时登录,或者想更好的模拟多个用户来登录系统. 这个时候就需要对用户名和密码进 ...

  10. 欧拉工程第53题:Combinatoric selections

    package projecteuler51to60; class p53{ void solve1(){ int count=0; int Max=1000000; int[][] table=ne ...