OSDN Git Service

Merge "simpleperf: fix app_profiler.py." am: d98c857902 am: 5ea663c3ab am: 545ee30d39
[android-x86/system-extras.git] / simpleperf / README.md
1 # Simpleperf
2
3 Simpleperf is a native profiling tool for Android. It can be used to profile
4 both Android applications and native processes running on Android. It can
5 profile both Java and C++ code on Android. It can be used on Android L
6 and above.
7
8 Simpleperf is part of the Android Open Source Project. The source code is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/).
9 The latest document is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/README.md).
10 Bugs and feature requests can be submitted at http://github.com/android-ndk/ndk/issues.
11
12
13 ## Table of Contents
14
15 - [Simpleperf introduction](#simpleperf-introduction)
16     - [Why simpleperf](#why-simpleperf)
17     - [Tools in simpleperf](#tools-in-simpleperf)
18     - [Simpleperf's profiling principle](#simpleperfs-profiling-principle)
19     - [Main simpleperf commands](#main-simpleperf-commands)
20         - [Simpleperf list](#simpleperf-list)
21         - [Simpleperf stat](#simpleperf-stat)
22         - [Simpleperf record](#simpleperf-record)
23         - [Simpleperf report](#simpleperf-report)
24 - [Android application profiling](#android-application-profiling)
25     - [Prepare an Android application](#prepare-an-android-application)
26     - [Record and report profiling data (using command-lines)](#record-and-report-profiling-data-using-commandlines)
27     - [Record and report profiling data (using python scripts)](#record-and-report-profiling-data-using-python-scripts)
28     - [Record and report call graph](#record-and-report-call-graph)
29     - [Visualize profiling data](#visualize-profiling-data)
30     - [Annotate source code](#annotate-source-code)
31
32
33 ## Simpleperf introduction
34
35 ### Why simpleperf
36
37 Simpleperf works similar to linux-tools-perf, but it has some specific features for
38 Android profiling:
39
40 1. Aware of Android environment
41
42     a. It can profile embedded shared libraries in apk.
43
44     b. It reads symbols and debug information from .gnu_debugdata section.
45
46     c. It gives suggestions when errors occur.
47
48     d. When recording with -g option, unwind the stack before writting to file to
49     save storage space.
50
51     e. It supports adding additional information (like symbols) in perf.data, to
52     support recording on device and reporting on host.
53
54 2. Using python scripts for profiling tasks
55
56 3. Easy to release
57
58     a. Simpleperf executables on device are built as static binaries. They can be
59     pushed on any Android device and run.
60
61     b. Simpleperf executables on host are built as static binaries, and support
62     different hosts: mac, linux and windows.
63
64
65 ### Tools in simpleperf
66
67 Simpleperf is periodically released with Android ndk, located at `simpleperf/`.
68 The latest release can be found [here](https://android.googlesource.com/platform/prebuilts/simpleperf/).
69 Simpleperf tools contain executables, shared libraries and python scripts.
70
71 **Simpleperf executables running on Android device**
72 Simpleperf executables running on Android device are located at `bin/android/`.
73 Each architecture has one executable, like `bin/android/arm64/simpleperf`. It
74 can record and report profiling data. It provides a command-line interface
75 broadly the same as the linux-tools perf, and also supports some additional
76 features for Android-specific profiling.
77
78 **Simpleperf executables running on hosts**
79 Simpleperf executables running on hosts are located at `bin/darwin`, `bin/linux`
80 and `bin/windows`. Each host and architecture has one executable, like
81 `bin/linux/x86_64/simpleperf`. It provides a command-line interface for
82 reporting profiling data on hosts.
83
84 **Simpleperf report shared libraries used on host**
85 Simpleperf report shared libraries used on host are located at `bin/darwin`,
86 `bin/linux` and `bin/windows`. Each host and architecture has one library, like
87 `bin/linux/x86_64/libsimpleperf_report.so`. It is a library for parsing
88 profiling data.
89
90 **Python scripts**
91 Python scripts are written to help different profiling tasks.
92
93 `annotate.py` is used to annotate source files based on profiling data.
94
95 `app_profiler.py` is used to profile Android applications.
96
97 `binary_cache_builder.py` is used to pull libraries from Android devices.
98
99 `pprof_proto_generator.py` is used to convert profiling data to format used by pprof.
100
101 `report.py` is used to provide a GUI interface to report profiling result.
102
103 `report_sample.py` is used to generate flamegraph.
104
105 `simpleperf_report_lib.py` provides a python interface for parsing profiling data.
106
107
108 ### Simpleperf's profiling principle
109
110 Modern CPUs have a hardware component called the performance monitoring unit
111 (PMU). The PMU has several hardware counters, counting events like how many cpu
112 cycles have happened, how many instructions have executed, or how many cache
113 misses have happened.
114
115 The Linux kernel wraps these hardware counters into hardware perf events. In
116 addition, the Linux kernel also provides hardware independent software events
117 and tracepoint events. The Linux kernel exposes all this to userspace via the
118 perf_event_open system call, which simpleperf uses.
119
120 Simpleperf has three main functions: stat, record and report.
121
122 The stat command gives a summary of how many events have happened in the
123 profiled processes in a time period. Here’s how it works:
124 1. Given user options, simpleperf enables profiling by making a system call to
125 linux kernel.
126 2. Linux kernel enables counters while scheduling on the profiled processes.
127 3. After profiling, simpleperf reads counters from linux kernel, and reports a
128 counter summary.
129
130 The record command records samples of the profiled process in a time period.
131 Here’s how it works:
132 1. Given user options, simpleperf enables profiling by making a system call to
133 linux kernel.
134 2. Simpleperf creates mapped buffers between simpleperf and linux kernel.
135 3. Linux kernel enable counters while scheduling on the profiled processes.
136 4. Each time a given number of events happen, linux kernel dumps a sample to a
137 mapped buffer.
138 5. Simpleperf reads samples from the mapped buffers and generates perf.data.
139
140 The report command reads a "perf.data" file and any shared libraries used by
141 the profiled processes, and outputs a report showing where the time was spent.
142
143
144 ### Main simpleperf commands
145
146 Simpleperf supports several subcommands, including list, stat, record and report.
147 Each subcommand supports different options. This section only covers the most
148 important subcommands and options. To see all subcommands and options,
149 use --help.
150
151     # List all subcommands.
152     $ simpleperf --help
153
154     # Print help message for record subcommand.
155     $ simpleperf record --help
156
157
158 #### Simpleperf list
159
160 simpleperf list is used to list all events available on the device. Different
161 devices may support different events because of differences in hardware and
162 kernel.
163
164     $ simpleperf list
165     List of hw-cache events:
166       branch-loads
167       ...
168     List of hardware events:
169       cpu-cycles
170       instructions
171       ...
172     List of software events:
173       cpu-clock
174       task-clock
175       ...
176
177
178 #### Simpleperf stat
179
180 simpleperf stat is used to get a raw event counter information of the profiled program
181 or system-wide. By passing options, we can select which events to use, which
182 processes/threads to monitor, how long to monitor and the print interval.
183 Below is an example.
184
185     # Stat using default events (cpu-cycles,instructions,...), and monitor
186     # process 7394 for 10 seconds.
187     $ simpleperf stat -p 7394 --duration 10
188     Performance counter statistics:
189
190      1,320,496,145  cpu-cycles         # 0.131736 GHz                     (100%)
191        510,426,028  instructions       # 2.587047 cycles per instruction  (100%)
192          4,692,338  branch-misses      # 468.118 K/sec                    (100%)
193     886.008130(ms)  task-clock         # 0.088390 cpus used               (100%)
194                753  context-switches   # 75.121 /sec                      (100%)
195                870  page-faults        # 86.793 /sec                      (100%)
196
197     Total test time: 10.023829 seconds.
198
199 **Select events**
200 We can select which events to use via -e option. Below are examples:
201
202     # Stat event cpu-cycles.
203     $ simpleperf stat -e cpu-cycles -p 11904 --duration 10
204
205     # Stat event cache-references and cache-misses.
206     $ simpleperf stat -e cache-references,cache-misses -p 11904 --duration 10
207
208 When running the stat command, if the number of hardware events is larger than
209 the number of hardware counters available in the PMU, the kernel shares hardware
210 counters between events, so each event is only monitored for part of the total
211 time. In the example below, there is a percentage at the end of each row,
212 showing the percentage of the total time that each event was actually monitored.
213
214     # Stat using event cache-references, cache-references:u,....
215     $ simpleperf stat -p 7394 -e     cache-references,cache-references:u,cache-references:k,cache-misses,cache-misses:u,cache-misses:k,instructions --duration 1
216     Performance counter statistics:
217
218     4,331,018  cache-references     # 4.861 M/sec    (87%)
219     3,064,089  cache-references:u   # 3.439 M/sec    (87%)
220     1,364,959  cache-references:k   # 1.532 M/sec    (87%)
221        91,721  cache-misses         # 102.918 K/sec  (87%)
222        45,735  cache-misses:u       # 51.327 K/sec   (87%)
223        38,447  cache-misses:k       # 43.131 K/sec   (87%)
224     9,688,515  instructions         # 10.561 M/sec   (89%)
225
226     Total test time: 1.026802 seconds.
227
228 In the example above, each event is monitored about 87% of the total time. But
229 there is no guarantee that any pair of events are always monitored at the same
230 time. If we want to have some events monitored at the same time, we can use
231 --group option. Below is an example.
232
233     # Stat using event cache-references, cache-references:u,....
234     $ simpleperf stat -p 7394 --group cache-references,cache-misses --group cache-references:u,cache-misses:u --group cache-references:k,cache-misses:k -e instructions --duration 1
235     Performance counter statistics:
236
237     3,638,900  cache-references     # 4.786 M/sec          (74%)
238        65,171  cache-misses         # 1.790953% miss rate  (74%)
239     2,390,433  cache-references:u   # 3.153 M/sec          (74%)
240        32,280  cache-misses:u       # 1.350383% miss rate  (74%)
241       879,035  cache-references:k   # 1.251 M/sec          (68%)
242        30,303  cache-misses:k       # 3.447303% miss rate  (68%)
243     8,921,161  instructions         # 10.070 M/sec         (86%)
244
245     Total test time: 1.029843 seconds.
246
247 **Select target to monitor**
248 We can select which processes or threads to monitor via -p option or -t option.
249 Monitoring a process is the same as monitoring all threads in the process.
250 Simpleperf can also fork a child process to run the new command and then monitor
251 the child process. Below are examples.
252
253     # Stat process 11904 and 11905.
254     $ simpleperf stat -p 11904,11905 --duration 10
255
256     # Stat thread 11904 and 11905.
257     $ simpleperf stat -t 11904,11905 --duration 10
258
259     # Start a child process running `ls`, and stat it.
260     $ simpleperf stat ls
261
262 **Decide how long to monitor**
263 When monitoring existing threads, we can use --duration option to decide how long
264 to monitor. When monitoring a child process running a new command, simpleperf
265 monitors until the child process ends. In this case, we can use Ctrl-C to stop monitoring
266 at any time. Below are examples.
267
268     # Stat process 11904 for 10 seconds.
269     $ simpleperf stat -p 11904 --duration 10
270
271     # Stat until the child process running `ls` finishes.
272     $ simpleperf stat ls
273
274     # Stop monitoring using Ctrl-C.
275     $ simpleperf stat -p 11904 --duration 10
276     ^C
277
278 **Decide the print interval**
279 When monitoring perf counters, we can also use --interval option to decide the print
280 interval. Below are examples.
281
282     # Print stat for process 11904 every 300ms.
283     $ simpleperf stat -p 11904 --duration 10 --interval 300
284
285     # Print system wide stat at interval of 300ms for 10 seconds (rooted device only).
286     # system wide profiling needs root privilege
287     $ su 0 simpleperf stat -a --duration 10 --interval 300
288
289 **Display counters in systrace**
290 simpleperf can also work with systrace to dump counters in the collected trace.
291 Below is an example to do a system wide stat
292
293     # capture instructions (kernel only) and cache misses with interval of 300 milliseconds for 15 seconds
294     $ su 0 simpleperf stat -e instructions:k,cache-misses -a --interval 300 --duration 15
295     # on host launch systrace to collect trace for 10 seconds
296     (HOST)$ external/chromium-trace/systrace.py --time=10 -o new.html sched gfx view
297     # open the collected new.html in browser and perf counters will be shown up
298
299
300 #### Simpleperf record
301
302 simpleperf record is used to dump records of the profiled program. By passing
303 options, we can select which events to use, which processes/threads to monitor,
304 what frequency to dump records, how long to monitor, and where to store records.
305
306     # Record on process 7394 for 10 seconds, using default event (cpu-cycles),
307     # using default sample frequency (4000 samples per second), writing records
308     # to perf.data.
309     $ simpleperf record -p 7394 --duration 10
310     simpleperf I 07-11 21:44:11 17522 17522 cmd_record.cpp:316] Samples recorded: 21430. Samples lost: 0.
311
312 **Select events**
313 In most cases, the cpu-cycles event is used to evaluate consumed cpu time.
314 As a hardware event, it is both accurate and efficient. We can also use other
315 events via -e option. Below is an example.
316
317     # Record using event instructions.
318     $ simpleperf record -e instructions -p 11904 --duration 10
319
320 **Select target to monitor**
321 The way to select target in record command is similar to that in stat command.
322 Below are examples.
323
324     # Record process 11904 and 11905.
325     $ simpleperf record -p 11904,11905 --duration 10
326
327     # Record thread 11904 and 11905.
328     $ simpleperf record -t 11904,11905 --duration 10
329
330     # Record a child process running `ls`.
331     $ simpleperf record ls
332
333 **Set the frequency to record**
334 We can set the frequency to dump records via the -f or -c options. For example,
335 -f 4000 means dumping approximately 4000 records every second when the monitored
336 thread runs. If a monitored thread runs 0.2s in one second (it can be preempted
337 or blocked in other times), simpleperf dumps about 4000 * 0.2 / 1.0 = 800
338 records every second. Another way is using -c option. For example, -c 10000
339 means dumping one record whenever 10000 events happen. Below are examples.
340
341     # Record with sample frequency 1000: sample 1000 times every second running.
342     $ simpleperf record -f 1000 -p 11904,11905 --duration 10
343
344     # Record with sample period 100000: sample 1 time every 100000 events.
345     $ simpleperf record -c 100000 -t 11904,11905 --duration 10
346
347 **Decide how long to monitor**
348 The way to decide how long to monitor in record command is similar to that in
349 stat command. Below are examples.
350
351     # Record process 11904 for 10 seconds.
352     $ simpleperf record -p 11904 --duration 10
353
354     # Record until the child process running `ls` finishes.
355     $ simpleperf record ls
356
357     # Stop monitoring using Ctrl-C.
358     $ simpleperf record -p 11904 --duration 10
359     ^C
360
361 **Set the path to store records**
362 By default, simpleperf stores records in perf.data in current directory. We can
363 use -o option to set the path to store records. Below is an example.
364
365     # Write records to data/perf2.data.
366     $ simpleperf record -p 11904 -o data/perf2.data --duration 10
367
368
369 #### Simpleperf report
370
371 simpleperf report is used to report based on perf.data generated by simpleperf
372 record command. Report command groups records into different sample entries,
373 sorts sample entries based on how many events each sample entry contains, and
374 prints out each sample entry. By passing options, we can select where to find
375 perf.data and executable binaries used by the monitored program, filter out
376 uninteresting records, and decide how to group records.
377
378 Below is an example. Records are grouped into 4 sample entries, each entry is
379 a row. There are several columns, each column shows piece of information
380 belonging to a sample entry. The first column is Overhead, which shows the
381 percentage of events inside current sample entry in total events. As the
382 perf event is cpu-cycles, the overhead can be seen as the percentage of cpu
383 time used in each function.
384
385     # Reports perf.data, using only records sampled in libsudo-game-jni.so,
386     # grouping records using thread name(comm), process id(pid), thread id(tid),
387     # function name(symbol), and showing sample count for each row.
388     $ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so --sort comm,pid,tid,symbol -n
389     Cmdline: /data/data/com.example.sudogame/simpleperf record -p 7394 --duration 10
390     Arch: arm64
391     Event: cpu-cycles (type 0, config 0)
392     Samples: 28235
393     Event count: 546356211
394
395     Overhead  Sample  Command    Pid   Tid   Symbol
396     59.25%    16680   sudogame  7394  7394  checkValid(Board const&, int, int)
397     20.42%    5620    sudogame  7394  7394  canFindSolution_r(Board&, int, int)
398     13.82%    4088    sudogame  7394  7394  randomBlock_r(Board&, int, int, int, int, int)
399     6.24%     1756    sudogame  7394  7394  @plt
400
401 **Set the path to read records**
402 By default, simpleperf reads perf.data in current directory. We can use -i
403 option to select another file to read records.
404
405     $ simpleperf report -i data/perf2.data
406
407 **Set the path to find executable binaries**
408 If reporting function symbols, simpleperf needs to read executable binaries
409 used by the monitored processes to get symbol table and debug information. By
410 default, the paths are the executable binaries used by monitored processes while
411 recording. However, these binaries may not exist when reporting or not contain
412 symbol table and debug information. So we can use --symfs to redirect the paths.
413 Below is an example.
414
415     $ simpleperf report
416     # In this case, when simpleperf wants to read executable binary /A/b,
417     # it reads file in /A/b.
418
419     $ simpleperf report --symfs /debug_dir
420     # In this case, when simpleperf wants to read executable binary /A/b,
421     # it prefers file in /debug_dir/A/b to file in /A/b.
422
423 **Filter records**
424 When reporting, it happens that not all records are of interest. Simpleperf
425 supports five filters to select records of interest. Below are examples.
426
427     # Report records in threads having name sudogame.
428     $ simpleperf report --comms sudogame
429
430     # Report records in process 7394 or 7395
431     $ simpleperf report --pids 7394,7395
432
433     # Report records in thread 7394 or 7395.
434     $ simpleperf report --tids 7394,7395
435
436     # Report records in libsudo-game-jni.so.
437     $ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so
438
439     # Report records in function checkValid or canFindSolution_r.
440     $ simpleperf report --symbols "checkValid(Board const&, int, int);canFindSolution_r(Board&, int, int)"
441
442 **Decide how to group records into sample entries**
443 Simpleperf uses --sort option to decide how to group sample entries. Below are
444 examples.
445
446     # Group records based on their process id: records having the same process
447     # id are in the same sample entry.
448     $ simpleperf report --sort pid
449
450     # Group records based on their thread id and thread comm: records having
451     # the same thread id and thread name are in the same sample entry.
452     $ simpleperf report --sort tid,comm
453
454     # Group records based on their binary and function: records in the same
455     # binary and function are in the same sample entry.
456     $ simpleperf report --sort dso,symbol
457
458     # Default option: --sort comm,pid,tid,dso,symbol. Group records in the same
459     # thread, and belong to the same function in the same binary.
460     $ simpleperf report
461
462
463 ## Android application profiling
464
465 This section shows how to profile an Android application.
466 [Here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/README.md) are examples. And we use
467 [SimpleperfExamplePureJava](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExamplePureJava) project to show the profiling results.
468
469 Simpleperf only supports profiling native instructions in binaries in ELF
470 format. If the Java code is executed by interpreter, or with jit cache, it
471 can’t be profiled by simpleperf. As Android supports Ahead-of-time compilation,
472 it can compile Java bytecode into native instructions with debug information.
473 On devices with Android version <= M, we need root privilege to compile Java
474 bytecode with debug information. However, on devices with Android version >= N,
475 we don't need root privilege to do so.
476
477 Profiling an Android application involves three steps:
478 1. Prepare the application.
479 2. Record profiling data.
480 3. Report profiling data.
481
482 To profile, we can use either command lines or python scripts. Below shows both.
483
484
485 ### Prepare an Android application
486
487 Before profiling, we need to install the application to be profiled on an Android device.
488 To get valid profiling results, please check following points:
489
490 **1. The application should be debuggable.**
491 It means [android:debuggable](https://developer.android.com/guide/topics/manifest/application-element.html#debug)
492 should be true. So we need to use debug [build type](https://developer.android.com/studio/build/build-variants.html#build-types)
493 instead of release build type. It is understandable because we can't profile others' apps.
494 However, on a rooted Android device, the application doesn't need to be debuggable.
495
496 **2. Run on an Android device >= L.**
497 Profiling on emulators are not yet supported. And to profile Java code, we need
498 the jvm running in oat mode, which is only available >= L.
499
500 **3. On Android O, add `wrap.sh` in the apk.**
501 To profile Java code, we need the jvm running in oat mode. But on Android O,
502 debuggable applications are forced to run in jit mode. To work around this,
503 we need to add a `wrap.sh` in the apk. So if you are running on Android O device,
504 Check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExamplePureJava/app/profiling.gradle)
505 for how to add `wrap.sh` in the apk.
506
507 **4. Make sure C++ code is compiled with optimizing flags.**
508 If the application contains C++ code, it can be compiled with -O0 flag in debug build type.
509 This makes C++ code slow. Check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExamplePureJava/app/profiling.gradle)
510 for how to avoid that.
511
512 **5. Use native libraries with debug info in the apk when possible.**
513 If the application contains C++ code or pre-compiled native libraries, try to use
514 unstripped libraries in the apk. This helps simpleperf generating better profiling
515 results. Check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExamplePureJava/app/profiling.gradle)
516 for how to use unstripped libraries.
517
518 Here we use [SimpleperfExamplePureJava](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExamplePureJava) as an example.
519 It builds an app-profiling.apk for profiling.
520
521     $ git clone https://android.googlesource.com/platform/system/extras
522     $ cd extras/simpleperf/demo
523     # Open SimpleperfExamplesPureJava project with Android studio,
524     # and build this project sucessfully, otherwise the `./gradlew` command below will fail.
525     $ cd SimpleperfExamplePureJava
526
527     # On windows, use "gradlew" instead.
528     $ ./gradlew clean assemble
529     $ adb install -r app/build/outputs/apk/app-profiling.apk
530
531
532 ### Record and report profiling data (using command-lines)
533
534 We recommend using python scripts for profiling because they are more convenient.
535 But using command-line will give us a better understanding of the profile process
536 step by step. So we first show how to use command lines.
537
538 **1. Enable profiling**
539
540     $ adb shell setprop security.perf_harden 0
541
542 **2. Fully compile the app**
543
544 We need to compile Java bytecode into native instructions to profile Java code
545 in the application. This needs different commands on different Android versions.
546
547 On Android >= N:
548
549     $ adb shell setprop debug.generate-debug-info true
550     $ adb shell cmd package compile -f -m speed com.example.simpleperf.simpleperfexamplepurejava
551     # Restart the app to take effect
552     $ adb shell am force-stop com.example.simpleperf.simpleperfexamplepurejava
553
554 On Android M devices, We need root privilege to force Android to fully compile
555 Java code into native instructions in ELF binaries with debug information. We
556 also need root privilege to read compiled native binaries (because installd
557 writes them to a directory whose uid/gid is system:install). So profiling Java
558 code can only be done on rooted devices.
559
560     $ adb root
561     $ adb shell setprop dalvik.vm.dex2oat-flags -g
562
563     # Reinstall the app.
564     $ adb install -r app/build/outputs/apk/app-profiling.apk
565
566 On Android L devices, we also need root privilege to compile the app with debug info
567 and access the native binaries.
568
569     $ adb root
570     $ adb shell setprop dalvik.vm.dex2oat-flags --include-debug-symbols
571
572     # Reinstall the app.
573     $ adb install -r app/build/outputs/apk/app-profiling.apk
574
575
576 **3. Find the app process**
577
578     # Start the app if needed
579     $ adb shell am start -n com.example.simpleperf.simpleperfexamplepurejava/.MainActivity
580
581     # Run `ps` in the app's context. On Android >= O devicces, run `ps -e` instead.
582     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava ps | grep simpleperf
583     u0_a151   6885  3346  1590504 53980 SyS_epoll_ 6fc2024b6c S com.example.simpleperf.simpleperfexamplepurejava
584
585 So the id of the app process is `6885`. We will use this number in the command lines below,
586 please replace this number with what you get by running `ps` command.
587
588 **4. Download simpleperf to the app's data directory**
589
590     # Find which architecture the app is using.
591     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava cat /proc/6885/maps | grep boot.oat
592     708e6000-70e33000 r--p 00000000 103:09 1214                              /system/framework/arm64/boot.oat
593
594     # The app uses /arm64/boot.oat, so push simpleperf in bin/android/arm64/ to device.
595     $ cd ../../scripts/
596     $ adb push bin/android/arm64/simpleperf /data/local/tmp
597     $ adb shell chmod a+x /data/local/tmp/simpleperf
598     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava cp /data/local/tmp/simpleperf .
599
600
601 **5. Record perf.data**
602
603     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava ./simpleperf record -p 6885 --duration 10
604     simpleperf I 04-27 20:41:11  6940  6940 cmd_record.cpp:357] Samples recorded: 40008. Samples lost: 0.
605
606     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava ls -lh perf.data
607     simpleperf I 04-27 20:31:40  5999  5999 cmd_record.cpp:357] Samples recorded: 39949. Samples lost: 0.
608
609 The profiling data is recorded at perf.data.
610
611 Normally we need to use the app when profiling, otherwise we may record no samples.
612 But in this case, the MainActivity starts a busy thread. So we don't need to use
613 the app while profiling.
614
615 There are many options to record profiling data, check [record command](#simpleperf-record) for details.
616
617 **6. Report perf.data**
618
619     # Pull perf.data on host.
620     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava cat perf.data >perf.data
621
622     # Report samples using corresponding simpleperf executable on host.
623     # On windows, use "bin\windows\x86_64\simpleperf" instead.
624     $ bin/linux/x86_64/simpleperf report
625     ...
626     Overhead  Command   Pid   Tid   Shared Object                                                                     Symbol
627     83.54%    Thread-2  6885  6900  /data/app/com.example.simpleperf.simpleperfexamplepurejava-2/oat/arm64/base.odex  void com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.run()
628     16.11%    Thread-2  6885  6900  /data/app/com.example.simpleperf.simpleperfexamplepurejava-2/oat/arm64/base.odex  int com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.callFunction(int)
629
630 There are many ways to show reports, check [report command](#simpleperf-report) for details.
631
632
633 ### Record and report profiling data (using python scripts)
634
635 Besides command lines, We can use `app-profiler.py` to profile Android applications.
636 It downloads simpleperf on device, records perf.data, and collects profiling
637 results and native binaries on host. It is configured by `app-profiler.config`.
638
639 **1. Fill `app-profiler.config`**
640
641     Change `app_package_name` line to  app_package_name="com.example.simpleperf.simpleperfexamplepurejava"
642     Change `apk_file_path` line to apk_file_path = "../SimpleperfExamplePureJava/app/build/outputs/apk/app-profiling.apk"
643     Change `android_studio_project_dir` line to android_studio_project_dir = "../SimpleperfExamplePureJava/"
644     Change `record_options` line to record_options = "--duration 10"
645
646 `apk_file_path` is needed to fully compile the application on Android L/M. It is
647 not necessary on Android >= N.
648
649 `android_studio_project_dir` is used to search native libraries in the
650 application. It is not necessary for profiling.
651
652 `record_options` can be set to any option accepted by simpleperf record command.
653
654 **2. Run `app-profiler.py`**
655
656     $ python app_profiler.py
657
658
659 If running successfully, it will collect profiling data in perf.data in current
660 directory, and related native binaries in binary_cache/.
661
662 **3. Report perf.data**
663
664 We can use `report.py` to report perf.data.
665
666     $ python report.py
667
668 We can add any option accepted by `simpleperf report` command to `report.py`.
669
670
671 ### Record and report call graph
672
673 A call graph is a tree showing function call relations. Below is an example.
674
675     main() {
676         FunctionOne();
677         FunctionTwo();
678     }
679     FunctionOne() {
680         FunctionTwo();
681         FunctionThree();
682     }
683     callgraph:
684         main-> FunctionOne
685            |    |
686            |    |-> FunctionTwo
687            |    |-> FunctionThree
688            |
689            |-> FunctionTwo
690
691
692 #### Record dwarf based call graph
693
694 When using command lines, add `-g` option like below:
695
696     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava ./simpleperf record -g -p 6685 --duration 10
697
698 When using python scripts, change `app-profiler.config` as below:
699
700     Change `record_options` line to record_options = "--duration 10 -g"
701
702 Recording dwarf based call graph needs support of debug information
703 in native binaries. So if using native libraries in the application,
704 it is better to contain non-stripped native libraries in the apk.
705
706
707 #### Record stack frame based call graph
708
709 When using command lines, add `--call-graph fp` option like below:
710
711     $ adb shell run-as com.example.simpleperf.simpleperfexamplepurejava ./simpleperf record --call-graph fp -p 6685 --duration 10
712
713 When using python scripts, change `app-profiler.config` as below:
714
715     Change `record_options` line to record_options = "--duration 10 --call-graph fp"
716
717 Recording stack frame based call graphs needs support of stack frame
718 register. Notice that on arm architecture, the stack frame register
719 is not well supported, even if compiled using -O0 -g -fno-omit-frame-pointer
720 options. It is because the kernel can't unwind user stack containing both
721 arm/thumb code. **So please consider using dwarf based call graph on arm
722 architecture, or profiling in arm64 environment.**
723
724
725 #### Report call graph
726
727 To report call graph using command lines, add `-g` option.
728
729     $ bin/linux/x86_64/simpleperf report -g
730     ...
731     Children  Self    Command          Pid    Tid    Shared Object                                                                     Symbol
732     99.97%    0.00%   Thread-2         10859  10876  /system/framework/arm64/boot.oat                                                  java.lang.Thread.run
733        |
734        -- java.lang.Thread.run
735           |
736            -- void com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.run()
737                |--83.66%-- [hit in function]
738                |
739                |--16.22%-- int com.example.simpleperf.simpleperfexamplepurejava.MainActivity$1.callFunction(int)
740                |    |--99.97%-- [hit in function]
741
742 To report call graph using python scripts, add `-g` option.
743
744     $ python report.py -g
745     # Double-click an item started with '+' to show its callgraph.
746
747 ### Visualize profiling data
748
749 `simpleperf_report_lib.py` provides an interface reading samples from perf.data.
750 By using it, You can write python scripts to read perf.data or convert perf.data
751 to other formats. Below are two examples.
752
753
754 ### Show flamegraph
755
756     $ python report_sample.py >out.perf
757     $ stackcollapse-perf.pl out.perf >out.folded
758     $ ./flamegraph.pl out.folded >a.svg
759
760
761 ### Visualize using pprof
762
763 pprof is a tool for visualization and analysis of profiling data. It can
764 be got from https://github.com/google/pprof. pprof_proto_generator.py can
765 generate profiling data in a format acceptable by pprof.
766
767     $ python pprof_proto_generator.py
768     $ pprof -pdf pprof.profile
769
770
771 ### Annotate source code
772
773 `annotate.py` reads perf.data, binaries in `binary-cache` (collected by `app-profiler.py`)
774 and source code, and generates annoated source code in `annotated_files/`.
775
776 It is configured by `annotate.config`.
777
778 **1. Fill `annotate.config`**
779
780     Change `source_dirs` line to source_dirs = ["../SimpleperfExamplePureJava"]
781     Change `addr2line_path` line to addr2line_path = "addr2line"
782
783 `addr2line` is need to annotate source code. It can be found in Android ndk release.
784 Please set `addr2line_path` to the location of `addr2line` if it can't be found
785 in PATH environment variable.
786
787 **2. Run `annotate.py`**
788
789     $ python annotate.py
790
791
792 **3. Read annotated code**
793
794 The annotated source code is located at `annotated_files/`.
795 `annotated_files/summary` shows how each source file is annotated.
796
797 One annotated source file is `annotated_files/java/com/example/simpleperf/simpleperfexamplepurejava/MainActivity.java`.
798 It's content is similar to below:
799
800     // [file] shows how much time is spent in current file.
801     /* [file] acc_p: 99.966552%, p: 99.837438% */package com.example.simpleperf.simpleperfexamplepurejava;
802     ...
803     // [func] shows how much time is spent in current function.
804     /* [func] acc_p: 16.213395%, p: 16.209250% */            private int callFunction(int a) {
805     ...
806     // This shows how much time is spent in current line.
807     // acc_p field means how much time is spent in current line and functions called by current line.
808     // p field means how much time is spent just in current line.
809     /* acc_p: 99.966552%, p: 83.628188%        */                    i = callFunction(i);
810