Share
Embed
Droidcon Santo Domingo 2017 - Android Performance for everyone
This talk took place in Santo Domingo, Dominican Republic during the first #Droidcon in Latinamerica on March 3rd and 4th, 2017.
http://droidcon.do
Carlos Daniel
March 04, 2017
Transcript
203 slides
-
Carlos Daniel Munoz I. - Android Dev @cdmunozi [email protected] Co-Founder
& Co-Organizer @MedellinAndroid March 3-4, 2017 DROIDCON REPÚBLICA DOMINICANA Android Performance for everyone -
“Success is no accident. It is hard work, perseverance, learning,
studying, sacrifice and most of all, love of what you are doing or learning to do. “ - Pelé -
1. Identifying and diagnosing performance problems 2. Exploratory Tests 3.
Profiling tools 4. Using outputs 5. Designing plans of attack 6. How program code and Android platform interact -
The only way to fast is to go well (
The higher the quality, the faster you go ) -
13 Why is my app slow? Imagine this app: •
Great app • A screen with a list -
14 Why is my app slow? Imagine this app: •
Great app • A screen with a list • With animations for every item within a list -
15 Why is my app slow? Imagine this app: •
Great app • A screen with a list • With animations for every item within a list • Overlays -
16 Why is my app slow? Imagine this app: •
Great app • A screen with a list • With animations for every item within a list • Overlays • Transparencies -
17 Why is my app slow? Imagine this app: •
Great app • A screen with a list • With animations for every item within a list • Overlays • Transparencies • May change the order of the items with a drag gesture -
19 Why rendering performance matters • Great app, with animations
for every item within a list, overlays, transparencies -
20 Why rendering performance matters • Great app, with animations
for every item within a list, overlays, transparencies • Problems with views (tons of views), slow app -
21 Why rendering performance matters • Great app, with animations
for every item within a list, overlays, transparencies • Problems with views (tons of views), slow app • What to do? (I want to keep the user experience) -
23 Visual Design vs Performance? • Android always try to
redraw the activity every 16 milliseconds → 60 frames per seconds including views and logic -
24 Visual Design vs Performance? • Android always try to
redraw the activity every 16 milliseconds → 60 frames per seconds including views and logic • If there is a problem → dropped frame → freezes until it finishes → no smoothed animations -
25 Rendering Pipeline: common problems • CPU: unnecessary views and
invalidations → view hierarchy • GPU: overdraw → wasting GPU processing time coloring in pixels F L O W -
26 Android UI and the GPU • Rasterization • GPU
accelerates rasterization process → polygons and textures • CPU feeding the GPU • CPU + GPU using API OpenGL ES • All resources within an Android Theme are grouped into a single texture and then uploaded into the GPU (this types of views fast) • GPU bottleneck → overdraw -
28 GPU Problem: Overdraw • How many times a pixel
is being redrawn on the screen in a single frame ◦ Stack of UI cards → wasting GPU performance -
29 GPU Problem: Overdraw • How many times a pixel
is being redrawn on the screen in a single frame ◦ Stack of UI cards → wasting GPU performance • How to see it? ◦ Go to Settings > Developer Options ◦ Turn on Debug GPU Overdraw. ◦ In the popup, choose Show overdraw areas. -
30 GPU Problem: Overdraw • How many times a pixel
is being redrawn on the screen in a single frame ◦ Stack of UI cards → wasting GPU performance • How to see it? ◦ Go to Settings > Developer Options ◦ Turn on Debug GPU Overdraw. ◦ In the popup, choose Show overdraw areas. • As the overdraw increases, so do the colors -
31 GPU Problem: Overdraw • How many times a pixel
is being redrawn on the screen in a single frame ◦ Stack of UI cards → wasting GPU performance • How to see it? ◦ Go to Settings > Developer Options ◦ Turn on Debug GPU Overdraw. ◦ In the popup, choose Show overdraw areas. • As the overdraw increases, so do the colors -
34 Visualize and fixes Overdraw • What did we see?
◦ Layouts setting background in every layout of a list ◦ Not Nullifying background of the theme ◦ Setting transparencies where required and colors -
39 clipRect and quickReject • Canvas.clipRect → everything outside this
canvas, ignore it -
40 clipRect and quickReject • Canvas.clipRect → everything outside this
canvas, ignore it • Canvas.quickReject → tests whether a given area is completely outside the clipping rectangle -
43 Fixing overdraw with Canvas API • Custom Views: ◦
In onDraw() → Canvas.save() → Canvas.clipRect() → Canvas.restore() Hidden, do not draw -
45 Hierarchy Viewer • Tools → Android → Android Device
Monitor • Flatten the view tree to save memory • Profile to see if a view is taking more time to load -
46 Hierarchy Viewer • Tools → Android → Android Device
Monitor • Flatten the view tree to save memory • Profile to see if a view is taking more time to load -
48 Nested Hierarchies and Performance • Inflating layouts is a
very expensive process -
49 Nested Hierarchies and Performance • Inflating layouts is a
very expensive process • Every nested layout impacts the performance -
50 Nested Hierarchies and Performance • Inflating layouts is a
very expensive process • Every nested layout impacts the performance • Example of Items of a list using several linear layouts and using a relative layout to flattens the view → Show profile in Hierarchy View -
53 Slow Function Performance How we write our code affects
the performance, depending on how the language executes in the hardware!!!! -
54 Slow Function Performance • Find a single slow function,
then fix the code and gotcha! -
55 Slow Function Performance • Find a single slow function,
then fix the code and gotcha! • What if we have 1.000 functions, every one lasting 1 additional millisecond? -
56 Slow Function Performance • Find a single slow function,
then fix the code and gotcha! • What if we have 1.000 functions, every one lasting 1 additional millisecond? -
57 Slow Function Performance • Find a single slow function,
then fix the code and gotcha! • What if we have 1.000 functions, every one lasting 1 additional millisecond? • Is there any tool to track this? -
59 Trace View • Great information resource: ◦ Time spent
executing method | CPU time | Call + Recursion -
60 Trace View • Great information resource: ◦ Time spent
executing method | CPU time | Call + Recursion • Tools → Android → Android Device Monitor → DDMS -
61 Trace View • Tools → Android → Android Device
Monitor → DDMS -
62 Trace View • Tools → Android → Android Device
Monitor → DDMS -
63 Trace View • Great information resource: ◦ Time spent
executing method | CPU time | Call + Recursion -
64 Trace View • The exclusive time → time spent
just in the method itself, which can help you find issues within that specific method. -
65 Trace View • The exclusive time → time spent
just in the method itself, which can help you find issues within that specific method. • The inclusive time → is for the method and all methods it calls, which can help you find problems with your call tree. -
66 Trace View • The exclusive time → time spent
just in the method itself, which can help you find issues within that specific method. • The inclusive time → is for the method and all methods it calls, which can help you find problems with your call tree. • The Calls+Rec → how many times a method was called recursively, which can help you track down performance issues. -
68 Batching and caching • Batch and cache as strategies
to improve performance -
69 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! -
70 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! • Batching → Solves this problem trying to eliminate the per execution overhead -
71 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! • Batching → Solves this problem trying to eliminate the per execution overhead ◦ Sharing a car instead of everyone driving themselves to save gas -
72 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! • Batching → Solves this problem trying to eliminate the per execution overhead ◦ Sharing a car instead of everyone driving themselves to save gas • Example of caching an operation value that is calculated in a loop and always has the same result -
73 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! • Batching → Solves this problem trying to eliminate the per execution overhead ◦ Sharing a car instead of everyone driving themselves to save gas • Example of caching an operation value that is calculated in a loop and always has the same result • Caching → it’s easy to CPU to access the RAM instead of hard drives -
74 Batching and caching • Batch and cache as strategies
to improve performance • Example: Loading data into a new place in memory before execution → Execution multiple times (really big number) → Overhead? → Sure! • Batching → Solves this problem trying to eliminate the per execution overhead ◦ Sharing a car instead of everyone driving themselves to save gas • Example of caching an operation value that is calculated in a loop and always has the same result • Caching → it’s easy to CPU to access the RAM instead of hard drives • COMPUTE FIBONACCI EXAMPLE -
77 Fixing Fibonacci • Change recursive way, then use a
procedural way storing previous values -
80 Blocking the UI Thread • Remember the 16 ms
frame set? → After 5 seconds → ANR -
85 Container Performance • Take into account (Basic cannon in
modern data structures): -
86 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements -
87 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements ◦ Perform a search (unsorted)? -
88 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements ◦ Perform a search (unsorted)? ▪ Binary search : O(log(n)) -
89 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements ◦ Perform a search (unsorted)? ▪ Binary search : O(log(n)) ▪ Hash Table: O(1) -
90 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements ◦ Perform a search (unsorted)? ▪ Binary search : O(log(n)) ▪ Hash Table: O(1) • All of this, the language provides it -
91 Container Performance • Take into account (Basic cannon in
modern data structures): ◦ Quicksort is faster than Bubble sort after a thousand elements ◦ Perform a search (unsorted)? ▪ Binary search : O(log(n)) ▪ Hash Table: O(1) • All of this, the language provides it • Problems with performance? → regarding this containers -
92 Container Performance • James Sutherland → microbenchmarks* on java
containers performance * https://java-persistence-performance.blogspot.com.co/2010/12/what-is-faster-jvm-performance.html -
95 Tracing App Code • Using Trace* package we can
add signals to our code * https://developer.android.com/studio/profile/systrace-walkthru.html -
96 Tracing App Code • Using Trace* package we can
add signals to our code ◦ Trace.beginSection(String) * https://developer.android.com/studio/profile/systrace-walkthru.html -
97 Tracing App Code • Using Trace* package we can
add signals to our code ◦ Trace.beginSection(String) ◦ Trace.endSection() * https://developer.android.com/studio/profile/systrace-walkthru.html -
98 Tracing App Code • Using Trace* package we can
add signals to our code ◦ Trace.beginSection(String) ◦ Trace.endSection() • This technique → what work our application's threads are doing at any given time Example: dumpPopularRandomNumbersByRank() * https://developer.android.com/studio/profile/systrace-walkthru.html -
99 Tracing App Code • Using Trace* package we can
add signals to our code ◦ Trace.beginSection(String) ◦ Trace.endSection() • This technique can help us see what work our application's threads are doing at any given time (Example: dumpPopularRandomNumbersByRank() ) ◦ NOTES: ▪ Python installed ▪ adb ok (export PATH=$PATH:~/android-sdks/platform-tools ) ▪ systrace enabled → python systrace.py --time=10 -o mynewtrace.html sched gfx view wm * https://developer.android.com/studio/profile/systrace-walkthru.html -
105 Tracing App Code Improvement notes: • There’s always a
one-time cost to sort items (you'd pick the ideal sorting item according to the size of your dataset). -
106 Tracing App Code Improvement notes: • There’s always a
one-time cost to sort items (you'd pick the ideal sorting item according to the size of your dataset). • By using a HashMap, we save time by obtaining a linear look-up time (O(n)) vs. the quadratic time O(n^2) access of the array in the unoptimized case. We save this one order of access time because the data is already stored in key value pairs! -
107 Tracing App Code Improvement notes: • There’s always a
one-time cost to sort items (you'd pick the ideal sorting item according to the size of your dataset). • By using a HashMap, we save time by obtaining a linear look-up time (O(n)) vs. the quadratic time O(n^2) access of the array in the unoptimized case. We save this one order of access time because the data is already stored in key value pairs! • This matters significantly when n (or the sample size) is particularly large, which may be the case if you were working with, say, a list of all professional football players in the world and wanted to display a ranking of them across some attribute. -
109 Memory and Garbage Collector “I can write code however
I want, Garbage Collector does the rest” -
113 Memory, GC and Performance • John McCarthy - 1959
• Solve problems with Lisp • 1 - 2 are easy in theory BUT complex when we have more lines of code • Fast and effective without interruptions -
114 Memory, GC and Performance • John McCarthy - 1959
• Solve problems with Lisp • 1 - 2 are easy in theory BUT complex when we have more lines of code • Fast and effective without interruptions -
116 Memory Monitor Tool • The more time is spent
doing GC, there will be less time to do other stuff -
117 Memory Monitor Tool • The more time is spent
doing GC, there will be less time to do other stuff • Example with an App -
118 Memory Monitor Tool • The more time is spent
doing GC, there will be less time to do other stuff • Example with an App • What happens if it reaches the maximum? ◦ The app is closed -
119 Memory Monitor Tool • The more time is spent
doing GC, there will be less time to do other stuff: rendering, streaming audio • Example with an App • What happens if it reaches the maximum? ◦ The app is closed • Who did this? ◦ GC -
124 Heap Viewer • Tool → Android Device Monitor ◦
See what type of object the app is allocating and how many and sizes of those objects -
125 Heap Viewer • Tool → Android Device Monitor ◦
See what type of object the app is allocating and how many and sizes of those objects -
127 Spotting Leaks in Memory Monitor • Have you experienced
mysterious slowdowns after using an app? -
128 Spotting Leaks in Memory Monitor • Have you experienced
mysterious slowdowns after using an app? • Patience - Perf mindset - Right Tools → abolish the leaks from the app. -
129 Spotting Leaks in Memory Monitor • Have you experienced
mysterious slowdowns after using an app? • Patience - Perf mindset - Right Tools → abolish the leaks from the app. • Example → Memory Leak ◦ Show Monitor behavior and Memory Monitor Heap Viewer Cause GC -
130 Spotting Leaks in Memory Monitor • Have you experienced
mysterious slowdowns after using an app? • Patience - Perf mindset - Right Tools → abolish the leaks from the app. • Example → Memory Leak ◦ Show Monitor behavior and Memory Monitor Heap Viewer Cause GC ◦ Changing orientation continuously -
131 Spotting Leaks in Memory Monitor • Have you experienced
mysterious slowdowns after using an app? • Patience - Perf mindset - Right Tools → abolish the leaks from the app. • Example → Memory Leak ◦ Show Monitor behavior and Memory Monitor Heap Viewer Cause GC ◦ Changing orientation continuously -
134 Memory Churn • Process to allocate lots of objects
in a very short amount of time that creates a lot of pressure to the heaps -
135 Memory Churn • Process to allocate lots of objects
in a very short amount of time that creates a lot of pressure to the heaps ◦ Allocating a bunch of objects (or heavy ones) in onDraw() -
136 Memory Churn • Process to allocate lots of objects
in a very short amount of time that creates a lot of pressure to the heaps ◦ Allocating a bunch of objects (or heavy ones) in onDraw() ◦ Allocating a load of temporary objects (or heavy ones) in a middle of a for loop -
137 Memory Churn • Process to allocate lots of objects
in a very short amount of time that creates a lot of pressure to the heaps ◦ Allocating a bunch of objects (or heavy ones) in onDraw() ◦ Allocating a load of temporary objects (or heavy ones) in a middle of a for loop -
139 Allocation Tracker • Tool in Android Studio • Android
Monitor → Monitors → Start Allocation Tracker -
140 Allocation Tracker • Tool in Android Studio • Android
Monitor → Monitors → Start Allocation Tracker -
141 Allocation Tracker • Tool in Android Studio • Android
Monitor → Monitors → Start Allocation Tracker • -
142 Allocation Tracker - Memory Churn • Running churn example
→ Creates a matrix, then “clones” it into a new one with sorted rows • Concatenating within the loop every new sorted row (Creates a new StringBuilder every new concatenation) -
143 Memory Churn - Solution • Running fixed churn example
→ Improvement • Still blocks UI, then is a candidate method to run in another thread -
146 Memory - Recap • Several handy tools ◦ Memory
monitor → View state of memory over time -
147 Memory - Recap • Several handy tools ◦ Memory
monitor → View state of memory over time ◦ Heat Viewer → What’s on the heap -
148 Memory - Recap • Several handy tools ◦ Memory
monitor → View state of memory over time ◦ Heat Viewer → What’s on the heap ◦ Allocation tracker → Where did it come from -
149 Memory - Recap • Several handy tools ◦ Memory
monitor → View state of memory over time ◦ Heat Viewer → What’s on the heap ◦ Allocation tracker → Where did it come from • Evaluate code against several tools and seek multiple perspectives -
152 Battery → The problem • Imagine an app that
is updating in real time the location of a user, keeping an active connection to more accurate results -
153 Battery → The problem • Imagine an app that
is updating in real time the location of a user, keeping an active connection to more accurate results -
156 Battery drain • How the process works under the
hood? ◦ Active phone: ▪ CPU processes ▪ cellular radio transmitting data ▪ screen awake - remember Render section? -
157 Battery drain • How the process works under the
hood? ◦ Active phone: ▪ CPU processes ▪ cellular radio transmitting data ▪ screen awake - remember Render section? ◦ Application awakening the device: ▪ Wake clock ▪ Alarm manager -
158 Battery drain • How the process works under the
hood? ◦ Active phone: ▪ CPU processes ▪ cellular radio transmitting data ▪ screen awake - remember Render section? ◦ Application awakening the device: ▪ Wake clock ▪ Alarm manager • How do I identify battery behavior? -
160 Battery Historian • Batterystats command from adb (gives an
illegible file) -
161 Battery Historian • Batterystats command from adb (gives an
illegible file) • Tool to analyze battery consumers using Android "bugreport" files -
162 Battery Historian • Batterystats command from adb (gives an
illegible file) • Tool to analyze battery consumers using Android "bugreport" files • Python script - https://github.com/google/battery-historian ◦ python history.py <stats_file> > <html_file> -
163 Battery Historian • Batterystats command from adb (gives an
illegible file) • Tool to analyze battery consumers using Android "bugreport" files • Python script - https://github.com/google/battery-historian ◦ python history.py <stats_file> > <html_file> • What we can see? ◦ How often and how long a process did use the battery, NOT how much battery was used by each action -
167 Battery Manager • Wait for docking ◦ Only apply
some kind of logic (heavy pictures just like applying a filter to an image only when device is charging) -
168 Battery Manager • Wait for docking ◦ Only apply
some kind of logic (heavy pictures just like applying a filter to an image only when device is charging) ◦ BatteryManager + IntentFilter(Intent.ACTION_BATTERY_CHANGED) -
169 Battery Manager • Wait for docking ◦ Only apply
some kind of logic (heavy pictures just like applying a filter to an image only when device is charging) ◦ BatteryManager + IntentFilter(Intent.ACTION_BATTERY_CHANGED) -
171 Wakelock and Battery Drain • Battery drain, When?? ◦
Apps constantly checking scoreboards (games) ◦ uploading photos ◦ downloading upates -
172 Wakelock and Battery Drain • Battery drain, When?? ◦
Apps constantly checking scoreboards (games) ◦ uploading photos ◦ downloading upates • Sleep deprivation -
173 Wakelock and Battery Drain • Battery drain, When?? ◦
Apps constantly checking scoreboards (games) ◦ uploading photos ◦ downloading upates • Sleep deprivation -
175 Wakelock and Battery Drain How to solve it? ◦
PowerManager.Wakelock API ◦ Keeps CPU running preventing screen to turn off ◦ Wakes phone up in future dates, do some work, sleep ◦ Defer some activities -
176 Wakelock and Battery Drain How to solve it? ◦
PowerManager.Wakelock API ◦ Keeps CPU running preventing screen to turn off ◦ Wakes phone up in future dates, do some work, sleep ◦ Defer some activities ▪ Wifi connected ▪ Charging -
177 Wakelock and Battery Drain How to solve it? ◦
PowerManager.Wakelock API ◦ Keeps CPU running preventing screen to turn off ◦ Wakes phone up in future dates, do some work, sleep ◦ Defer some activities ▪ Wifi connected ▪ Charging • Google play services • Apps updating • Check geofences • Re-take some failed process -
178 Wakelock and Battery Drain How to solve it? ◦
PowerManager.Wakelock API ◦ Keeps CPU running preventing screen to turn off ◦ Wakes phone up in future dates, do some work, sleep ◦ Defer some activities ▪ Wifi connected ▪ Charging • Google play services • Apps updating • Check geofences • Re-take some failed process -
180 Battery - Job Scheduler Hyper active apps (Project Volta
from Google IO 2014)* * https://www.youtube.com/watch?v=KzSKIpJepUw&feature=youtu.be -
181 Battery - Job Scheduler Hyper active apps (Project Volta
from Google IO 2014)* Shows activity of 50 simulated apps (wake up cycles) * https://www.youtube.com/watch?v=KzSKIpJepUw&feature=youtu.be -
182 Battery - Job Scheduler Hyper active apps (Project Volta
from Google IO 2014)* Shows activity of 50 simulated apps (wake up cycles) * https://www.youtube.com/watch?v=KzSKIpJepUw&feature=youtu.be -
183 Battery - Job Scheduler Hyper active apps (Project Volta
from Google IO 2014)* Shows activity of 50 simulated apps (wake up cycles) • What if multiple apps are doing wakelock.acquire inefficiently? ◦ Release the lock always after the job is done * https://www.youtube.com/watch?v=KzSKIpJepUw&feature=youtu.be -
184 Wakelock and Battery Drain Which is better? Mobile Radio
=== bad? Wifi === good? -
186 Job Scheduler • API to better run jobs, then
improve battery performance and efficiency. -
187 Job Scheduler • API to better run jobs, then
improve battery performance and efficiency. ◦ android.app.job.JobService -
188 Job Scheduler • API to better run jobs, then
improve battery performance and efficiency. ◦ android.app.job.JobService ◦ JobService always runs in main UI thread, then it’s important to better use a separate thread to do asynchronous work -
189 Job Scheduler • API to better run jobs, then
improve battery performance and efficiency. ◦ android.app.job.JobService ◦ JobService always runs in main UI thread, then it’s important to better use a separate thread to do asynchronous work • We can define jobs to run even only when the device is plugged in -
190 Reducing Network Access to Save Battery • Use JobScheduler
to minimize the cellular radio tax -
191 Reducing Network Access to Save Battery • Use JobScheduler
to minimize the cellular radio tax -
192 Reducing Network Access to Save Battery • Use JobScheduler
to minimize the cellular radio tax -
193 Reducing Network Access to Save Battery • Use JobScheduler
to minimize the cellular radio tax • Including JobInfo for particular requirements -
196 Battery Final thoughts • Profile an app using battery
historian • Identify within it opportunities where to use the JobScheduler API ◦ Look for inefficient wake lock and network access that can be fixed -
197 Battery Final thoughts • Profile an app using battery
historian • Identify within it opportunities where to use the JobScheduler API ◦ Look for inefficient wake lock and network access that can be fixed • Generate report and battery string and take a screenshot -
198 Battery Final thoughts • Profile an app using battery
historian • Identify within it opportunities where to use the JobScheduler API ◦ Look for inefficient wake lock and network access that can be fixed • Generate report and battery string and take a screenshot • Make improvements into the code (those sections identified as potentially inefficient or problematic) -
199 Battery Final thoughts • Profile an app using battery
historian • Identify within it opportunities where to use the JobScheduler API ◦ Look for inefficient wake lock and network access that can be fixed • Generate report and battery string and take a screenshot • Make improvements into the code (those sections identified as potentially inefficient or problematic) • Re-profile the code and generate a new battery report, then screenshot -
200 Battery Final thoughts • Profile an app using battery
historian • Identify within it opportunities where to use the JobScheduler API ◦ Look for inefficient wake lock and network access that can be fixed • Generate report and battery string and take a screenshot • Make improvements into the code (those sections identified as potentially inefficient or problematic) • Re-profile the code and generate a new battery report, then screenshot • Compare -
201 ...I’m not the best software developer, I’m a good
software developer with good practices...