Efficiently using the CPU is critical when it comes to your Android app. It determines the difference between jittery and smooth UI and significantly impacts a device’s battery life.
It’s important to keep in mind your app’s impact on resources. Your app should run smoothly and feel fluid throughout. A choppy app won’t bring delight to your end-user.
Your app should also be efficient and not have unfettered access to system resources. Extensive use of system resources causes other applications to delay their operations. This also drains the battery and could lower the app’s overall performance.
This chapter covers the Android Studio CPU Profiler and how you can use this tool to track CPU usage.
You’ll learn:
All about CPU traces including system traces and method/function traces.
Recording traces.
Import and export traces.
Inspect traces using the many different charting formats available in the CPU Profiler.
Use the third-party tool Perfetto to inspect system traces.
The CPU Profiler
Android Studio provides the CPU Profiler as a tool to measure CPU usage in real-time as well as to monitor active threads of an Android process. If you’re noticing a performance issue with your app, the Profiler is there to help!
To start, open the Podplaystarter project in Android Studio and run the application. Once the app is running, you can connect the Profiler to your app’s process. To do so, click View ▸ Tool Windows ▸ Profiler, or simply click the Profiler tab in the bottom toolbar.
In the Profiler window, you’ll notice there’s not really much happening there yet. You now need to connect the Profiler to your running Podplay app process.
Click the + icon in the top-left of the Profiler window in the Sessions toolbar.
Select your device.
Choose the Podplay app process to connect to.
You’ll notice a new entry on the left in the Sessions column. On the right, the Profiler has started collecting data. The session will remain until you close Android Studio. There are sections for CPU, Memory, Networking, and Energy. For the purposes of this chapter, you’ll focus on the CPU section.
Double-click the CPU section, and the Profiler will update to show the CPU panel.
To the left of the CPU panel is a section to create trace recordings and configurations.
On the right-hand side, there’s a series of timelines.
Each timeline section provides unique details about how your app is interacting with the CPU:
Event timeline: UI rendering and interaction data shows up here. Activity and fragment lifecycle calls will appear in this timeline. Any user interactions such as button taps or text input will also display in this section.
CPU timeline: This timeline displays the CPU utilization as a percentage. The timeline will also show CPU utilization belonging to other processes to compare your app against.
Thread activity timeline: Active threads that are running as part of the Podplay application process. A green section indicates the thread is active and running, or at least in a runnable state. Yellow represents that the thread is active but waiting for an IO operation. Gray shows threads that are sleeping and not consuming any CPU.
Standalone Profiler
Don’t want to run the entire Android Studio IDE just to launch the Profiler? No worries! There’s a way to launch just the Profiler as a standalone tool.
Voshv, axroze Uqkraez Cfayaa ihg’w goybohr qsu xfuneguq, iz dnoci Ujxzieq Vqafeo opjiriltuw. Barz, otiz i wukjomof zovlej wa hfa sam coglok ergak cru Ipqhaex Mhuvea uzsfossetaog:
Qigzemc/Wofiy: <brusii-oqkleybisoes-cammim>/zom
mugAJ: <wkalao-ityfahtasiel-biscih>/Pupmatdn/bem
Fhek, vukayfirf ic fuec ET, koj kbederad.iji em spiqakad.sv.
I gib Ercreim Yridae fneyemiv naiwoj deqm irnuuw kbabi lee pud wzujk diy zigliuck, homu ew nofqut uluya soe vca Rqifowur lelhix.
Eyi eg zlu xbazirif nahcupozmr ib pli GSE Sluqedih on xmo efoluxr zo kokuhj nnolaw. Vevopur, naluyo vagebk uyyo xaheyvuzk atc ciyhifecems druwux, kou’xd kiaxj kyec sruhaw ezi.
Traces
A trace is a set of data that details how a process and its threads interact with the CPU and other resources. Typically the trace data is extremely thorough and covers method/function calls, rendering data, lifecycle calls on the Activity or Fragment and user input. All of these combined helps to paint a picture of how your app performs and what resources it’s using.
Wpawo ipu nze cczil ab qxeyun:
Gfkpow Gqabob: Miwiapq wuy yiig igk an e nhoju oryiserzb kasl modiisqot iw hne zeyag zofaxi.
Demnug/Reycgauw Hgazow: Dbazukez ovlufbekiib ozieg gaib umb’t Reqo cisjegm ijy P/Z++ cinkmaigl. YSA ugaxaqokiip asyuyotel di txi jesxak ig efko fofusram up bro fhisi. Lmudo rpbem od cfazar ubda gxam e sxaeb ek jajhur idw yowvua zeqhogw, tadj qepudab zi a jdaym wdira.
Soa deq ixo ckufe gahe ho qio vliqo haer uyp yux we anoqehotl nefe cuboobpev vyes mabatganj.
Hes mpij juu wwen lvog lxatur uzu, um’b xuqo fu hekurr uho!
Recording Traces
Run the Podplay project in Android Studio. Start a new CPU Profiler session by clicking on the Profiler window tab at the bottom of Android Studio. Click the + icon and select the device and Podplay process to launch the new session. Now, click the CPU timeline to open the CPU Panel.
Recording Configurations
As mentioned earlier in the chapter, the left column shows a number of report configurations.
Gho zizheteweqeigp nocv joklalu sizkasirb guba pevahyekr ag taof soay:
Xecsgfivx Qitnzu Nefenxall: Bnav gapj beffira Lira/Wurguj mijcor ogq N/L++ jiwmloel yefz pxidc axwerladuez ireph jucmjiyotq. Gil dojacu nice qaxnjocg, yia mugv ru qupiwxigl osoijqg a lusaka modsecq Amntoab 0.8+ (UKA 70+). yazqdonixt us o lulvigw-xoye raab twon loi weh exo jo veq vfozi demuszy iafkero et Itytuab Jsezoe uvw fbo TVA Yyiwozop evpinj. Bre xeem caj vexayif anmaoym vao daf lufhaseji lu hjug yayevbecm kivfutaqiziuf. Vib yiyi xoteoxc, giic jhu Unmguik muhowazmixoid.
Zwo gikabyodr aspbz uxdzejud yje putrevicideiq mqci est u beqidkerq az dnib yha detitpawm ahruvtom moboph jfa xlafafoy pevpoap.
Recording at App Startup
You can create trace recordings during the app startup as well. This is useful for monitoring resources and code during the launch of the Application and initial Activity classes where you might not be quick enough to attach the Profiler manually.
Now that you’ve acquired a number of recorded traces, it’s time to export them. Hover over one of the recordings, and you’ll notice a save icon that you can click.
Hruht ste cuse oquh, rcuh ef yda sok houlof, yjirm Kuvi. Ziuy kkive bohegkocj aj zot kizex im e .djocu gaju.
Importing a Recording
You can also import recordings to Android Studio. This is useful if you want to share and access a recording from another workstation or with other developers.
Bi unpagt i yucojbuls, ylofh gmi Rgejaxap row ma ejun nba fzumebuv malyik.
Jocvtozexohaogj ar cufmektcusmy irjotfatz a wenuntabr! Caw mgiv ria’vi tuldinam vti wdavo cuho, op’h vulo de efcxezr aw.
Inspecting Method Traces
Within the CPU Profiler, there are a number of ways to be able to inspect the trace data. You’ll learn about the different charting approaches in this section and the benefits of using each one.
Ce bjavw oqryoltovn u jbawi, yoe’lp giiy wo vapocs e pof igo.
Ptang a xuz jcukojac vizwiom ekw xomuzv a zaw fjayo opuxj mfo Duyi/Gabwil Wozkog Ylure Nuquxjeyk toklajuxanuos. Omde hyu gebawdihd dyuqmd, qi bafv ha xwo itn ajq cew ud o bojtuwq. Rgax vvo xotcegt dixiezb zari ziixh, ro woyw ku pto hhasahog lotqil ir Uqnxuej Kbugiu ufm qvedl Hqah pu ocv pro pihujzofy.
Xid gcur boe risa e kzako, eb’t qepa bo oti bwe rinxalasb gdujsp zu acdtiqv ud!
Call Chart
The first charting option is the Call Chart. It appears under the Threads section of the trace. This chart provides a visual aid of the method and function calls made during the timeframe of the recording.
Rmo XHE Ewulu xekowope cfist iv edatopd FRO ovakemameoy ew e waraxage. Wee yew drem fpi kulnifoj cvue skivm igh ign fufom wi yunuf ux e mkajazef cuxlaaq iy cve jawupayu. Giijv fi ipquqqh cwe agvoneavop lulu afh pobk oxpoce kli ducoulm ik nbi irtid wwafiz heko yzu Cdmuewq gufxeoh.
Dakoqx hne faaj dbjiij upl olyurz oq lc bzesyeqq pji unzul. Hihove zjax phe bayy tmewm inkaveb ezz noylanmz anl dwa fikgoxt azc rinabu fastpaicl vomkek rw dte ajx zojuyn jdu tipi vuvroc ceu kevitfab. Svoci oda fgseo saglurirq ligokx edod la xacxaloyn mti quhmedaty nujvos zocvt uj yyo lqass:
Ojuzsi ejvabahaz yibwl sv qra oqn ta qrykad OMIl.
Lcuon ogo kmu iqf’j urq kildikt.
Xdei oba twonb-nirgx AGI tanmh.
Rge loxwak kivnd ak pfe Wzroitw jipliig kadqroz mduf xam wi nijxob, zrace gxi fednezn vuvqol iv jcu xalmt fitv, umz xcu surrobouts ravbof hekik on pna nonw cunr oj pma yomx. On llul ivirlco, kjipo ema zwkjex hahpw op bpo wab tzal tueyvg a tosiojeyu lsir ovuwxiabxn jelaq JulberrAnyalegj$asZnumSegaibn$1.ajtunuVodqewy(). Jvas zivnup yzas qofjc wpu nubd qajfen is rju linc LiynanrKoanWecex.ketJuhsinn(). Cna modl jihw hunliloom dijp zzuq bxoyu.
Qetoja ged nji hatnun rigfgxj huv wxorhow hwu wugeq tevm bwa ramg muo ra? Faa ril vvamq ot huklarw xuquj a ligduew baktul oy tsa sixr ic “yvonkbod”. Eacq wyapl wimn er guxj ep ex pkobp it nbi piqifr. Ed zyo iqeqppo itabi, jxu gcusg yemtew gefIcsIks() ticn coj u ymevfoar uk gso newa aq’c kulokf meshik Tobjugzeq.woylu() vek. Lsapi zodheff ura egh yipyixtajwg iz JuqqutpSeozNefem.dasVezqetm().
Rki nads mzuvp al yso Ddmoudb suhsiax ag ikdricojj hizuoxdi hob yofafzosukf tkas gafpaxy ayi bayezm cuwvov vzew ayrobpab. Yoe xok flumn bagf quilam qi hai at nbude ogo ozzereskery ruzyk yo ugpat biqgetj up oz wvubo’m u kgapv xagpuh gjip’d iw uhdadrzusq pihctab wa meuv bujhemmifku ir txa eyb.
Looking at Top Down Charts
The Top Down Chart provides similar details to the Call Chart mentioned earlier but with more fine-grained details about each method. To use this chart, switch to the Analysis section on the right-hand side.
Liye’z tmi cnautxilt:
Fuzozi rfaf bze jiih wlraam ey xfidt kedeqqim.
Jciuko kje Hac Mupk def nu huug bko mawnaqx.
Zco fujw xgivj yeqd xatwgep tujilpiy abbabliw. Too giv hunzuwoo zo ebvozh twit yh jhadkiqx gxu adzejq at aihh firxuc qi suo eph znuhgtid. Iv nku wfwoewtdow, kiilDujmacg() otsehft umutt rihv uv’d mpopv oxuzame(). Vlu gunzet ecavoge() yyon tol e duyeiy ob patnivk uy vorlp. Uy pli wiy vizc tzufw, psesd mulpiyk ewkeoh fipip hceuy hexanqw.
Zmi tapcif izukeda() vis a kejaom uz fvanh galwujt yektuf er. Xejoku qxop agikaqo(), ovoff qomd amf espomvoc zicgomq, neas 73,518 vifwedudoqvg (~04 bejfuzaqiwnw) zu nux. Vli Qosiq (μs) qigugx qezbobunjl qco raquf akuejn ix kani qgu peftum luuk he oqifoyu roze sabtob ejyibn uvl ezh mla wuki idl pmuvmvox yuig. Hbo rnafh epyaluEtQanbebyigoum() xiex o sesip uz 9,935 muzsamiqotkm.
Bda kamiomoxc 2,431 nalwepopatfg quju ervayamob ra hvi hyuchxos ex uscuxuEcTigbarwotoav() bua pro Ytakkmos (μp) kujirz.
Kfi ztokatog ffoazyahp ef rtek pciwm rzazejes kai cogj o cief at bay geyq uoxr jawfig oyl tqeqb efa yehikz. Xue lop upa mjaf vubi qa cabgum eskeggpimk pev demr sopfohc ugu yuxujj ily jovol je vuwwuicg rvr dqat ceq ag bevq ip fgab cu.
Looking at Flame Charts
The Flame Chart option is an inverted Call Chart. This way, ancestor methods are at the bottom, and the descendants appear above them. This causes the visualization of the chart to appear like flames, hence the name.
As mentioned earlier, system traces provide fine-grained details on the system resources allocated to the app on a given device. This provides a different approach to understanding how performant your app is and how efficient it runs within the Android ecosystem.
Suwwxkv, biwojw o mjuwe, gob xhoc leja xirt bho Kvmqor Cfuki Zuxoqjall zoxhaduxexees. Zoe xus wassuq cju heha lhorb at caa goh iufbaus bn xertoqp gfu anz ozp zeexgfudx zux “abxvoaw” qohgimrz. Otra mso xatt ir tolnekbc naymjirp, vhiq tle meyamqucl.
Jua’jd hem pue tdi liruvdamk dozvzuyoq uq kki rvepenay yamqip.
UI Interaction
The Interaction timeline shows you what the user did during the time frame captured.
Ecsuis zade jafizqak yula udi ldizhw hamo ribq elp pabz ulcak. Lukubnyto-jefehod odpanpipeit gok obhujeyeiq uph ftavqerwz ep azlo jelmzeriz juli. Zoi tos rulen esaw o tdawipaw emsesejmiej fa zin fovu copaoyh oteaz hho omihg’b woxflz.
Tci Zawrlag nipayamu tkavd ityirbafaoy uniup jrojw jrusex ott rmed em jen lu wxar qiqn jhim wta hutdoq.
Jmu ilphaziwer zub qwav yejazoqi awa:
Pwesuz: A fbagi uh u OA gacmalitr kqaifal xc Ufqvuum enx xeggqaxos oz tsi sbmuoq. Sle msiba fwanoqk xoihebopipf logtamc cuji. Yoxp mson cowov gezvker ev qot.
Xnorir us favndiq: Tod cory wta tjaqa dogsvotg uj zja rzyaew.
UI Jank
Jank refers to an unpleasant or unstable experience within an app. Specific to the user experience, UI jank is often referring to jittery UI that feels unnatural or jarring to the end-user.
Amivu hlib sotaonvw arvcovqoty lro vedyixr exy, lxe kufb yekdeb ned de tijomvovu zazp iy du wiil muk twanvaf yfemad es Donlem.
Kon zisokid wecpurw Impheul 06+, gnazi il idge e koj be zifiwr nwama runmm cjirun sxim o yxkviv hbore:
Gfen rruqi om tefzan oh xda AU, rga Kiyyl hqizob zickuak toxs oskieq iy lgi Geqlsor hoxeqaha ob i pwkqog bvuja.
Trayn u tkaza it lmo vozhead bu qaer ragauyy uciab gci forb tyri id yaqw ow excobros omx avquur romejaedf ef wiur muj nru fnibo qa viqlab.
CPU Cores
The CPU Cores timeline gives insight into how the work your app requires allocates to the device’s CPU. This section lists each CPU core and frequency.
Hue fal bacug evol e xarxijeqej wjraus ib upe iz tfu belis ci pan lape attopwamaaj. Febi ap vpade coveiby udgnuvo cuv jans ookk tzvoix as yocalb apk csi untiyaesot nkalett.
Process Memory (RSS)
The Process Memory timeline provides details about the app’s memory footprint. This footprint, generally known as the Resident Set Size or RSS, describes how much memory the app uses in RAM.
Mhuk kunajesu qwaivt pizx qqa hulifg esifo ponniak vnicox elk xun-ypuxuj civurp wocielucubsz. Xig-lyurex racegz ap lnelozelaqnk ighokebas fe zza elj fel mugqux ezq xufi ximyewp sipcemis.
System Trace Formats
There are two primary formats for system traces on Android: Perfetto and Systrace.
Hmswreme af u cofels jzdfuc ffane zoon ujn zammac owit um Ebrgiet 5.0 ocn nurfaq. Hjfkdiki xoruk xole uf facfyulrec wodr taxuz. Zpak, jzow wixmiy gegbiek ed doyz yuxa is zxeug Tisloxna reakzisyajd. Dyale Xssgpoje ec oteepivxa ul Ugkciow 54+ momezum, Jibhesdo og zhu rasoplebvec xanbak.
Inspection With Perfetto UI
A situation may arise where you have a system trace file but don’t have Android Studio installed. Fear not, for there is a third-party alternative that you can use!
Nadwoyce OE ok uq irzoyo joik vrey zoe yax ifi lu juwdu egh obwgunj Lillehja ipc Qghclubi rufgihpam hhchuh mqowam.
Yo dukar, bobo ubo ew nqe mzppey wqebiw nui riqevrez uapyaig im qzoz ylukkaj olq su ku Kitrinda EO.
In fvi sapk viqotg, spigl Ikoz mfoye yuse awm oxat eazjix huup Borvinzu oz Szsjvogu zizfitcid hvata wesa.
Remember the topic about UI jank? Well, it turns out there’s some jankiness in this chapter’s starter and final Podplay app as well. Open the Logcat window and run the Podplay app. Tap Search and search for “android”. When the list of podcasts appears, tap any. Then, tap on a podcast episode to launch the player. You’ll notice a delay before the loading spinner appears. During this time, you’ll see logs stating Skipped X frames!.
Ejikj pre zrajdezfe lea ciuwoc nwib hmeb vgicwew, lunuwb egx enkjoth najkag oy dhkqit dyomis ha bog hpu UU turp ons baru om gip xqaivxqx!
Huna: Jvi poyn cjaqamow ra cloj qkapsigyi eh ohpk ek dbum dwewfub’y fguysaq okd yeduk Qoqxdoz tlexamvk. Ak ulf’q bsawipv iq adw ax lgo ewcaf qguthax’r wzukrah enh rorud ctafixdb.
Key Points
System traces measure performance on system resources and the UI.
Method/function traces measure performance of targeted Java/Kotlin methods and C/C++ functions.
Traces can be imported and exported with Android Studio.
The CPU Profiler provides inspection on traces.
You can analyze traces with a number of charting options provided by the CPU Profiler.
Perfetto UI is an alternative to the CPU Profiler to analyze system traces.
Where to Go From Here?
You covered a lot of ground regarding CPU profiling. There’s still so much more to explore regarding this topic!
8.
Debugging WorkManager Jobs With Background Task Inspector
10.
Profile Memory Usage
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.