免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Investigating Your RAM Usage | Android Developers

Investigating Your RAM Usage

Because Android is designed for mobile devices, you should always be careful about how muchrandom-access memory (RAM) your app uses. Although Android’s Dalvik virtual machine performsroutine garbage collection, this doesn’t mean you can ignore when and where your app allocates andreleases memory. In order to provide a stable user experience that allows the system to quicklyswitch between apps, it’s important that your app does not needlessly consume memory when the useris not interacting with it.

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

Interpreting Log Messages


The simplest place to begin investigating your apps memory usage is the Dalvik log messages. You'llfind these log messages in logcat (the output isavailable in the Device Monitor or directly in IDEs such as Eclipse and Android Studio).

Every time a garbage collection occurs, logcat prints a message with the following information:

D/dalvikvm: <GC_Reason> <Amount_freed>, <Heap_stats>, <External_memory_stats>, <Pause_time>
GC Reason
What triggered the garbage collection and what kind of collection it is. Reasons that may appearinclude:
GC_CONCURRENT
A concurrent garbage collection that frees up memory as your heap begins to fill up.
GC_FOR_MALLOC
A garbage collection caused because your app attempted to allocate memory when your heap wasalready full, so the system had to stop your app and reclaim memory.
GC_HPROF_DUMP_HEAP
A garbage collection that occurs when you create an HPROF file to analyze your heap.
GC_EXPLICIT
An explicit garbage collection, such as when you call gc() (which youshould avoid calling and instead trust the garbage collector to run when needed).
GC_EXTERNAL_ALLOC
This happens only on API level 10 and lower (newer versions allocate everything in the Dalvikheap). A garbage collection for externally allocated memory (such as the pixel data stored innative memory or NIO byte buffers).
Amount freed
The amount of memory reclaimed from this garbage collection.
Heap stats
Percentage free and (number of live objects)/(total heap size).
External memory stats
Externally allocated memory on API level 10 and lower (amount of allocated memory) / (limit atwhich collection will occur).
Pause time
Larger heaps will have larger pause times. Concurrent pause times show two pauses: one at thebeginning of the collection and another near the end.

For example:

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

As these log messages stack up, look out for increases in the heap stats (the3571K/9991K value in the above example). If this valuecontinues to increase and doesn't ever seem to get smaller, you could have a memory leak.

Viewing Heap Updates


To get a little information about what kind of memory your app is using and when, you can viewreal-time updates to your app's heap in the 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 everygarbage collection. 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 garbagecollection. This can help you identify which actions in your app are likely causing too muchallocation and where you should try to reduce allocations and releaseresources.

Tracking Allocations


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

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

To use Allocation Tracker:

  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.
  5. Interact with your app to execute the code paths you want to analyze.
  6. Click Get Allocations every time you want to update thelist of 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 tothe allocation. The trace shows you not only what type of object was allocated, but also in whichthread, 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 else where that come from the allocation tracker itself.

Although it's not necessary (nor possible) to remove all allocations for your performancecritical 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.

Viewing Overall Memory Allocations


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

adb shell dumpsys meminfo <package_name>

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

When inspecting this information, you should be familiar with thefollowing 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 systemcan 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 itscontents exist only in RAM so can’t be paged to storage (because Android does not use swap). AllDalvik and native heap allocations you make will be private dirty RAM; Dalvik and nativeallocations you share with the Zygote process are 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 pagesthat are shared with other processes contribute to the PSS value only in proportion to the amountof sharing. For example, a page that is shared between two processes will contribute half of itssize to the PSS of each process.

A nice characteristic of the PSS measurement is that you can add up the PSS across all processes todetermine the actual memory being used by all processes. This means PSS is a good measure for theactual RAM weight of a process and for comparison against the RAM use of other processes and thetotal available RAM.

For example, below is the the output for Gmail’s process on a tablet device. There is a lot ofinformation here, but key points for discussion are listed below.

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

** 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 Dirtycolumns. In some cases, the Private Clean and Heap Alloc columns also offerinteresting data. Here is some more information about the different memory allocations (the rows)you should observe:

Dalvik Heap
The RAM used by Dalvik allocations in your app. The Pss Total includes all Zygoteallocations (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 ofyour own allocations and any Zygote allocation pages that have been modified since forking yourapp’s process from Zygote.

Note: On newer platform versions that have the DalvikOther section, the Pss Total and Private Dirty numbers for Dalvik Heap donot include Dalvik overhead such as the just-in-time compilation (JIT) and garbage collection (GC)bookkeeping, whereas older versions list it all combined under Dalvik.

The Heap Alloc is the amount of memory that the Dalvik and native heap allocators keeptrack of for your app. This value is larger than Pss Total and Private Dirtybecause your process was forked from Zygote and it includes allocations that your process shareswith all the others.

.so mmap and .dex mmap
The RAM being used for mmapped .so (native) and .dex (Dalvik) code. ThePss Total number includes platform code shared across apps; the Private Clean isyour app’s own code. Generally, the actual mapped size will be much larger—the RAM here is onlywhat currently needs to be in RAM for code that has been executed by the app. However, the .so mmaphas a large private dirty, which is due to fix-ups to the native code when it was loaded into itsfinal address.
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 whencollecting this data due to Address Space Layout Randomization (ASLR). As with the Dalvik heap, thePss Total for Unknown takes into account sharing with Zygote, and Private Dirtyis unknown RAM dedicated to only your app.
TOTAL
The total Proportional Set Size (PSS) RAM used by your process. This is the sum of all PSS fieldsabove it. It indicates the overall memory weight of your process, which can be directly comparedwith other processes and the total available RAM.

The Private Dirty and Private Clean are the total allocations within yourprocess, 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 noswap); clean RAM is pages that have been mapped from a persistent file (such as code beingexecuted) and so can be paged out if not used for a while.

ViewRootImpl
The number of root views that are active in your process. Each root view is associated with awindow, so this can help you identify memory leaks involving dialogs or other windows.
AppContexts and Activities
The number of app Context and Activity objects thatcurrently 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 soare a good way to track large memory leaks.

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.

Capturing a Heap Dump


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

To retrieve your heap dump:

  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.

If you need to be more precise about when the dump is created, you can also create a heap dumpat 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 JavaHPROF tool. The major difference in an Android heap dump is due to the fact that there are a largenumber of allocations in the Zygote process. But because the Zygote allocations are shared acrossall app processes, they don’t matter very much to your own heap analysis.

To analyze your heap dump, you can use a standard tool like jhat or the Eclipse Memory Analyzer Tool (MAT). However, firstyou'll need to convert the HPROF file from Android's format to the J2SE HPROF format. You can dothis using the hprof-conv tool provided in the <sdk>/tools/directory. Simply run the hprof-conv command with two arguments: the original HPROFfile and the location to write the converted HPROF file. For example:

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

Note: If you're using the version of DDMS that's integrated intoEclipse, you do not need to perform the HPROF converstion—it performs the conversion bydefault.

You can now load the converted file in MAT or another heap analysis tool that understandsthe J2SE HPROF format.

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

  • Long-lived references to an Activity, Context, View, Drawable, and other objects that may hold areference to the container Activity or Context.
  • Non-static inner classes (such as a Runnable, which can hold the Activity instance).
  • Caches that hold objects longer than necessary.

Using the Eclipse Memory Analyzer Tool

The Eclipse Memory Analyzer Tool (MAT) is just onetool that you can use to analyze your heap dump. It's also quite powerful so most of itscapabilities are beyond the scope of this document, but here are a few tips to get you started.

Once you open your converted HPROF file in MAT, you'll see a pie chart in the Overview,showing what your largest objects are. Below this chart, are links to couple of useful features:

  • The Histogram view shows a list of all classes and how many instances there are of each.

    You might want to use this view to find extra instances of classes for which you know there should be only a certain number. For example, a common source of leaks is additional instance of your Activity class, for which you should usually have only one instance at a time. To find a specific class instance, type the class name into the <Regex> field at the top of the list.

    When you find a class with too many instances, right-click it and select List objects > with incoming references. In the list that appears, you can determine where an instance is retained by right-clicking it and selecting Path To GC Roots > exclude weak references.

  • The Dominator tree shows a list of objects organized by the amount of retained heap.

    What you should look for is anything that's retaining a portion of heap that's roughly equivalent to the memory size you observed leaking from the GC logs, heap updates, or allocation tracker.

    When you see something suspicious, right-click on the item and select Path To GC Roots > exclude weak references. This opens a new tab that traces the references to that object which is causing the alleged leak.

    Note: Most apps will show an instance of Resources near the top with a good chunk of heap, but this is usually expected when your app uses lots of resources from your res/ directory.

Figure 4. The Eclipse Memory Analyzer Tool (MAT),showing the Histogram view and a search for "MainActivity".

For more information about MAT, watch the Google I/O 2011 presentation,Memory management for Android apps,which includes a walkthrough using MAT beginning at about 21:10.Also refer to the Eclipse MemoryAnalyzer documentation.

Comparing heap dumps

You may find it useful to compare your app's heap state at two different points in time in orderto inspect the changes in memory allocation. To compare two heap dumps using MAT:

  1. Create two HPROF files as described above, in Capturing a Heap Dump.
  2. Open the first HPROF file in MAT (File > Open Heap Dump).
  3. In the Navigation History view (if not visible, select Window > Navigation History), right-click on Histogram and select Add to Compare Basket.
  4. Open the second HPROF file and repeat steps 2 and 3.
  5. Switch to the Compare Basket view and click Compare the Results (the red "!" icon in the top-right corner of the view).

Triggering Memory Leaks


While using the tools described above, you should aggressively stress your app code and tryforcing memory leaks. One way to provoke memory leaks in your app is to let itrun for a while before inspecting the heap. Leaks will trickle up to the top of the allocations inthe 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 differentactivity states. Rotating the device can often cause an app to leak an Activity,Context, or View object because the systemrecreates the Activity and if your app holds a referenceto one of those objects somewhere else, the system can't garbage collect it.
  2. Switch between your app and another app while in different activity states (navigate tothe Home screen, then return to your app).

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 monkeyrunnerdocumentation.

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
ANDROID 探究oom內(nèi)幕
Android內(nèi)存分析和調(diào)優(yōu)(中)
Android Framework 框架之 Android 內(nèi)存管理
Android學(xué)習(xí)之 內(nèi)存管理機制與應(yīng)用內(nèi)存優(yōu)化
JVM分析工具鏈(三)- jstat和hprof
通過JMX控制在full GC前后做heap dump
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服