How to check the memory usage of Android applications and android

Source: Internet
Author: User

How to check the memory usage of Android applications and android

Android is designed for mobile devices, so pay attention to the memory usage of applications. Although Android's Dalvik virtual opportunity regularly performs garbage collection operations, it does not mean that you can ignore the application's memory allocation and release at any time. To provide a good user experience and ensure smooth system switching between different applications, it is important to avoid unnecessary memory consumption when users and applications do not interact.

Although the Principles in the management Your App Memory are well observed during the development process ), there may still be object leakage or introduce other memory bugs. The security measures that can be taken areAndroid code encryption and local data protectionAnd other security encryption technologies. For more information, seeLove Encryption, A professional smart service provider for mobile application security! The only way to determine that the application uses as little memory as possible is to use tools to analyze the memory usage of the application.

Parse log information

The most simple measure of application memory usage is the Dalvik log information. You can find the log information in logcat (output information can be viewed in Device Monitor or IDE, such as Eclipse and Android Studio. Every time a garbage collection occurs, logcat prints a log message with the following information:

D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>

GC reason

The reason for triggering garbage collection and the type of garbage collection. The reasons include:

GC_CONCURRENT

Concurrent garbage collection is triggered when the heap starts to fill up to release the memory.

GC_FOR_MALLOC

When the heap is full, the application tries to allocate the garbage collection triggered by memory. In this case, the system must pause the application to recycle the memory.

GC_HPROF_DUMP_HEAP

Create an HPROF file to analyze the garbage collection triggered by the application.

GC_EXPLICIT

Explicit garbage collection is triggered, for example, when gc () is called (manual call should be avoided, but the Garbage Collector must be called proactively when needed.

GC_EXTERNAL_ALLOC

This will only be available in API 10 and earlier versions (the new version of memory is only allocated in the Dalvik heap. Reclaim externally allocated memory (for example, pixel data stored in the local memory or NIO byte buffer ).

Release Quantity

The number of memories released after garbage collection.

Heap status

Percentage of idle and (number of active objects)/(total heap size ).

External memory status

Memory externally allocated in API 10 and earlier versions (the size of the allocated memory)/(the limit value when recycling occurs ).

Pause Time

The larger the heap, the longer the pause time. The pause time for concurrent recovery is divided into two parts: one is at the start of the collection, and the other is at the end of the collection.

For example:

D/dalvikvm( 9050): GC_CONCURRENT freed 2049K, 65% free 3571K/9991K, external 4703K/5261K, paused 2ms+2ms

As these log messages increase, pay attention to the changes in heap status (3571 K/9991 K in the preceding example. If the value keeps increasing and does not decrease, memory leakage may occur.

View heap updates

To obtain the application memory usage type and time, you can view application heap updates in Device Monitor in real time:

1. Enable Device Monitor.

Load the monitor tool from the <sdk>/tools/path.

2. In the Debug Monitor window, select the application process to be viewed from the process list on the left.

3. Click Update Heap in the process list.

4. Select the Heap tab on the right panel.

 

The Heap view displays the basic status of Heap memory usage, which is updated after each garbage collection. To view the updated status, click the Gause GC button.

Figure 1. The Device Monitor tool displays the [1] Update Heap and [2] Cause GC buttons. The Heap tab on the right shows the Heap status.

Trace memory allocation

To reduce memory problems, you should use Allocation Tracker to better understand the Allocation of large memory consumption users. Allocation Tracker is useful not only in viewing memory usage, but also in analyzing key code paths in applications, such as slide.

For example, you can track the memory allocation when sliding the list in the application, and you can see the memory allocation action, including the allocation on which threads and where. This is extremely useful for optimizing code paths to reduce workload and improve UI fluency.

Use Allocation Tracker:

1. Enable Device Monitor.

Load the monitor tool from the <sdk>/tools/path.

2. In the DDMS window, select an application process from the left-side pane.
3. Select the Allocation Tracker tab on the right panel.
4. Click Start Tracking.
5. Execute the application to the code path to be analyzed.
6. Click Get Allocations to update the allocation list.

The list shows all the currently allocated and 512-size ring buffers. Click the row to view the allocated stack trace information. The stack not only shows the allocated object type, but also the thread, the class, the file, and the row.


Figure 2. The Device Monitor tool displays the memory Allocation and stack trace of the current application in Allocation Tracker.

Note: there will always be some distributions from DdmVmInternal and allocation tracker itself.

Although removing all code that seriously affects performance is unnecessary (and impossible), allocation tracker can still help identify serious problems in the code. For example, an application may create a new Paint object in each draw operation. Changing an object to a global variable is a simple modification to improve performance.

View total memory allocation

For further analysis, you can use the following adb command to view the distribution of different memory types in the application memory:

adb shell dumpsys meminfo <package_name>

The current output list of memory allocation for the application, in kilobytes.

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

Private (Clean and Dirty) memory

Memory exclusive to the process. That is, the memory capacity that the system can directly recycle when the application process is destroyed. Generally, "private dirty" memory is the most important part, because it is only used by its own processes. It is only stored in memory, so it cannot be stored in external memory by PAGE (Android does not support swap ). All allocated Dalvik heap and local heap are "private dirty" memory. The shared dirty memory is used in the Dalvik heap and the local heap and the Zygote process.

Actual memory usage (PSS)

This is another computing method used by the application memory. The cross-process sharing page is also included. Any exclusive Memory Page directly calculates its PSS value, while pages shared with other processes calculate the PSS value based on the shared proportion. For example, on the pages shared between two processes, the PPS value calculated for each process is half the PPS size.

One advantage of the PSS calculation method is that the sum of the PSS values of all processes can determine the total memory occupied by all processes. This means that it is a good way to calculate the actual memory usage of processes, compare the memory usage between processes, and the total remaining memory size.

For example, below is the output of the Gmail process on a tablet device. It displays a lot of information, but the details are some of the key information listed below.

Note: The actual information may be slightly different from the information here. The output details may vary depending on the platform version.

** 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 only need to care about the Pss Total column and the Private Dirty column. In some cases, the Private Clean column and Heap Alloc column also provide useful information. Below are some memory allocation types that should be viewed (the types listed in the row ):

Dalvik Heap

The memory allocated by the Dalvik in the application. The Pss Total contains all Zygote distributions (as described in the preceding PSS definition, cross-process weighting is shared ). Private Dirty is the memory size exclusive to the application heap. It contains the allocated part of the memory and the Memory Page allocated by the application process when the Zygote replication is split.

Note: The new platform version includes Dalvik Other. The sum of Pss Total and Private Dirty in the Dalvik Heap does not cover the overhead of Dalvik, such as JIT and GC. However, the old version is included in the overhead of Dalvik.

Heap Alloc is the size allocated to the Dalvik Heap and local Heap in the application. The value is larger than the sum of Pss Total and Private Dirty, because the process is split from Zygote replication and contains the allocation part of process sharing.

. So mmap and. dex mmap

Memory Used by the. so (local) and. dex (Dalvik) codes mapped by mmap. Pss Total contains the platform code for cross-application sharing. Private Clean is the code for exclusive application sharing. Generally, the memory size of the actual ing is larger-the displayed memory size is the memory size used by the application after the current operation is executed. However, the private dirty of. so mmap is large because the memory space has been allocated to the local code when it is loaded to the final address.

Unknown

Cannot be classified into memory pages of other items. At present, this mainly includes the majority of local allocations, that is, those parts that cannot be calculated due to Address Space Layout Randomization (ASLR) Randomization during tool data collection. Like the Dalvik heap, the Pss Total in the Unknown calculates the portion shared with Zygote, and the Private Dirty in the Unknown calculates only the memory used by the application.

TOTAL

The actual memory used by the process is the sum of all the preceding PSS. It indicates the total memory usage of the process and can be used directly to compare with other processes or the total memory usage.

Private Dirty and Private Clean are the total memory occupied by processes independently and are not shared with other processes. When processes are destroyed, the memory occupied by them (especially Private Dirty) is released back to the system. Dirty memory is a modified Memory Page, so it must be resident in memory (because there is no swap); Clean memory is a memory page that has been mapped to persistent files (such as code being executed ), therefore, if you do not use it for a period of time, you can replace it.

ViewRootImpl

The number of active root views in the process. Each root view is associated with a window. Therefore, it helps determine the memory leakage involving the dialog box and window.

AppContexts and Activities

The number of Context and Activity objects that reside in the process. You can quickly identify common leaked Activity objects that cannot be recycled due to static references. These objects usually have many other associated allocations, so this is a good way to trace large memory leaks.

Note: View and Drawable objects also hold the reference of the Activity. Therefore, holding a View or Drawable object may also cause application Activity leakage.

Get heap dump

Heap dump is a snapshot of all objects in the application heap and is stored as a binary file HPROF. The application heap Dump provides the overall state of the application heap. Therefore, you can track issues that may have been confirmed while viewing heap updates.

Retrieve heap dump:

1. Enable Device Monitor.

Load the monitor tool from the <sdk>/tools/path.

2. In the DDMS window, select an application process from the left-side pane.

3. Click Dump HPROF file, as shown in figure 3.

4. In the pop-up window, name the HPROF file, select the storage location, and click Save.

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

You can call dumpHprofData () in the application code to generate a heap dump if you want to locate the problem more accurately.

The heap dump format is basically the same, but not the same as the Java HPROF file. The main difference between the Android heap dump is that many memory allocations are in the Zygote process. However, because Zygote memory allocation is shared by all application processes, it does not matter to analyze the application heap.

To analyze heap dump, you need a standard tool like jhat or Eclipse memory Analysis Tool (MAT. Of course, the first step is to convert the HPROF file from the Android file format to the J2SE HRPOF file format. You can use the hprof-conv tool in the <sdk>/platform-tools/path for conversion. Hprof-conv is easy to use. You only need to add two parameters: the original HPROF file and the storage location of the converted HPROF file. For example:

hprof-conv heap-original.hprof heap-converted.hprof

Note: If you are using DDMS integrated in Eclipse, you do not need to execute the HPROF conversion operation-the conversion has been completed by default.

Now you can load the converted HPROF file in MAT, or load it in other heap analysis tools that can parse J2SE HPROF format.

When analyzing the application heap, you should find the memory leakage caused by the following:

  • Long-term reference of Activity, Context, View, Drawable, and other objects that may be referenced by Activity or Context containers
  • Non-static internal class (for example, Runnable holding Activity instance)
  • Unnecessary caching of long-held objects
Use Eclipse memory analysis tools

Eclipse memory Analysis Tool (MAT) is a tool that can analyze heap dump. It is a powerful tool with far more functions than described in this document. Here is just an introduction to some beginners.

 

Open the type-converted HPROF file in MAT. On the overview page, a pie chart is displayed, showing the maximum object occupied by the heap. Below the chart is a link to several functions:

  • Histogram view displays the list of all classes and the number of instances of each class.

Normally, the number of instances of the class should be determined. You can use this view to find the instance of the additional class. For example, a common source code leak means that the Activity class has additional instances, and the correct one is that there should be only one instance at a time. To locate the instance of a specific class, enter the class name in the <Regex> field at the top of the list.

When a class has too many instances, right-click and choose List objects> with incoming references. In the displayed list, right-click and choose Path To GC Roots> exclude weak references To determine the reserved instance.

  • Dominator tree is a list of objects displayed based on the heap size.

It should be noted that the size of the remaining parts of the heap is roughly equal to the size of the leaked Objects Observed by GC logs, heap updates, or allocation tracker.

When a suspicious item is displayed, right-click and choose Path To GC Roots> exclude weak references. Open a new tab that lists references to suspicious objects.

Note: Most applications display Resources instances near the top of a large heap in the pie chart, but this is generally because the application uses many Resources in the res/path.

Figure 4. MAT shows the Histogram view and search for "MainActivity" results.

To obtain

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.