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/doc/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 - [Introduction](#introduction)
16 - [Tools in simpleperf](#tools-in-simpleperf)
17 - [Android application profiling](#android-application-profiling)
18 - [Prepare an Android application](#prepare-an-android-application)
19 - [Record and report profiling data](#record-and-report-profiling-data)
20 - [Record and report call graph](#record-and-report-call-graph)
21 - [Report in html interface](#report-in-html-interface)
22 - [Show flame graph](#show-flame-graph)
23 - [Record both on CPU time and off CPU time](#record-both-on-cpu-time-and-off-cpu-time)
24 - [Profile from launch](#profile-from-launch)
25 - [Parse profiling data manually](#parse-profiling-data-manually)
26 - [Executable commands reference](#executable-commands-reference)
27 - [How does simpleperf work?](#how-does-simpleperf-work)
28 - [Commands](#commands)
29 - [The list command](#the-list-command)
30 - [The stat command](#the-stat-command)
31 - [Select events to stat](#select-events-to-stat)
32 - [Select target to stat](#select-target-to-stat)
33 - [Decide how long to stat](#decide-how-long-to-stat)
34 - [Decide the print interval](#decide-the-print-interval)
35 - [Display counters in systrace](#display-counters-in-systrace)
36 - [The record command](#the-record-command)
37 - [Select events to record](#select-events-to-record)
38 - [Select target to record](#select-target-to-record)
39 - [Set the frequency to record](#set-the-frequency-to-record)
40 - [Decide how long to record](#decide-how-long-to-record)
41 - [Set the path to store profiling data](#set-the-path-to-store-profiling-data)
42 - [Record call graphs](#record-call-graphs-in-record-cmd)
43 - [Record both on CPU time and off CPU time](#record-both-on-cpu-time-and-off-cpu-time-in-record-cmd)
44 - [The report command](#the-report-command)
45 - [Set the path to read profiling data](#set-the-path-to-read-profiling-data)
46 - [Set the path to find binaries](#set-the-path-to-find-binaries)
47 - [Filter samples](#filter-samples)
48 - [Group samples into sample entries](#group-samples-into-sample-entries)
49 - [Report call graphs](#report-call-graphs-in-report-cmd)
50 - [Scripts reference](#scripts-reference)
51 - [app_profiler py](#app_profiler-py)
52 - [Profile from launch of an application](#profile-from-launch-of-an-application)
53 - [binary_cache_builder.py](#binary_cache_builder-py)
54 - [run_simpleperf_on_device.py](#run_simpleperf_on_device-py)
55 - [report.py](#report-py)
56 - [report_html.py](#report_html-py)
57 - [inferno](#inferno)
58 - [pprof_proto_generator.py](#pprof_proto_generator-py)
59 - [report_sample.py](#report_sample-py)
60 - [simpleperf_report_lib.py](#simpleperf_report_lib-py)
61 - [Answers to common issues](#answers-to-common-issues)
62 - [Why we suggest profiling on android >= N devices](#why-we-suggest-profiling-on-android-n-devices)
63 - [Suggestions about recording call graphs](#suggestions-about-recording-call-graphs)
64 - [How to solve missing symbols in report](#how-to-solve-missing-symbols-in-report)
65
66 ## Introduction
67
68 Simpleperf contains two parts: the simpleperf executable and Python scripts.
69
70 The simpleperf executable works similar to linux-tools-perf, but has some specific features for
71 the Android profiling environment:
72
73 1. It collects more info in profiling data. Since the common workflow is "record on the device, and
74 report on the host", simpleperf not only collects samples in profiling data, but also collects
75 needed symbols, device info and recording time.
76
77 2. It delivers new features for recording.
78 a. When recording dwarf based call graph, simpleperf unwinds the stack before writing a sample
79 to file. This is to save storage space on the device.
80 b. Support tracing both on CPU time and off CPU time with --trace-offcpu option.
81
82 3. It relates closely to the Android platform.
83 a. Is aware of Android environment, like using system properties to enable profiling, using
84 run-as to profile in application's context.
85 b. Supports reading symbols and debug information from the .gnu_debugdata section, because
86 system libraries are built with .gnu_debugdata section starting from Android O.
87 c. Supports profiling shared libraries embedded in apk files.
88 d. It uses the standard Android stack unwinder, so its results are consistent with all other
89 Android tools.
90
91 4. It builds executables and shared libraries for different usages.
92 a. Builds static executables on the device. Since static executables don't rely on any library,
93 simpleperf executables can be pushed on any Android device and used to record profiling data.
94 b. Builds executables on different hosts: Linux, Mac and Windows. These executables can be used
95 to report on hosts.
96 c. Builds report shared libraries on different hosts. The report library is used by different
97 Python scripts to parse profiling data.
98
99 Detailed documentation for the simpleperf executable is [here](#executable-commands-reference).
100
101 Python scripts are split into three parts according to their functions:
102
103 1. Scripts used for simplifying recording, like app_profiler.py.
104
105 2. Scripts used for reporting, like report.py, report_html.py, inferno.
106
107 3. Scripts used for parsing profiling data, like simpleperf_report_lib.py.
108
109 Detailed documentation for the Python scripts is [here](#scripts-reference).
110
111 ## Tools in simpleperf
112
113 The simpleperf executables and Python scripts are located in simpleperf/ in ndk releases, and in
114 system/extras/simpleperf/scripts/ in AOSP. Their functions are listed below.
115
116 bin/: contains executables and shared libraries.
117
118 bin/android/${arch}/simpleperf: static simpleperf executables used on the device.
119
120 bin/${host}/${arch}/simpleperf: simpleperf executables used on the host, only supports reporting.
121
122 bin/${host}/${arch}/libsimpleperf_report.${so/dylib/dll}: report shared libraries used on the host.
123
124 [app_profiler.py](#app_profiler-py): recording profiling data.
125
126 [binary_cache_builder.py](#binary_cache_builder-py): building binary cache for profiling data.
127
128 [report.py](#report-py): reporting in stdio interface.
129
130 [report_html.py](#report_html-py): reporting in html interface.
131
132 [inferno.sh](#inferno) (or inferno.bat on Windows): generating flamegraph in html interface.
133
134 inferno/: implementation of inferno. Used by inferno.sh.
135
136 [pprof_proto_generator.py](#pprof_proto_generator-py): converting profiling data to the format
137 used by [pprof](https://github.com/google/pprof).
138
139 [report_sample.py](#report_sample-py): converting profiling data to the format used by [FlameGraph](https://github.com/brendangregg/FlameGraph).
140
141 [simpleperf_report_lib.py](#simpleperf_report_lib-py): library for parsing profiling data.
142
143
144 ## Android application profiling
145
146 This section shows how to profile an Android application.
147 Some examples are [Here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/README.md).
148
149 Simpleperf only supports profiling native instructions in binaries in ELF format. If the Java code
150 is executed by interpreter, or with jit cache, it cant be profiled by simpleperf. As Android
151 supports Ahead-of-time compilation, it can compile Java bytecode into native instructions with
152 debug information. On devices with Android version <= M, we need root privilege to compile Java
153 bytecode with debug information. However, on devices with Android version >= N, we don't need
154 root privilege to do so.
155
156 Profiling an Android application involves three steps:
157 1. Prepare the application.
158 2. Record profiling data.
159 3. Report profiling data.
160
161 ### Prepare an Android application
162
163 Before profiling, we need to install the application on Android device. To get valid profiling
164 results, please check following items:
165
166 1. The application should be debuggable.
167 Security restrictions mean that only apps with android::debuggable set to true can be profiled.
168 (On a rooted device, all apps can be profiled.) In Android Studio, that means you need to use
169 the debug build type instead of the release build type.
170
171 2. Run on an Android >= N device.
172 [We suggest profiling on an Android >= N device](#why-we-suggest-profiling-on-android-n-devices).
173
174 3. On Android O, add `wrap.sh` in the apk.
175 To profile Java code, we need ART running in oat mode. But on Android O, debuggable applications
176 are forced to run in jit mode. To work around this, we need to add a `wrap.sh` in the apk. So if
177 you are running on Android O device and need to profile Java code, add `wrap.sh` as [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle).
178
179 4. Make sure C++ code is compiled with optimizing flags.
180 If the application contains C++ code, it can be compiled with -O0 flag in debug build type.
181 This makes C++ code slow, to avoid that, check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle).
182
183 5. Use native libraries with debug info in the apk when possible.
184 If the application contains C++ code or pre-compiled native libraries, try to use unstripped
185 libraries in the apk. This helps simpleperf generating better profiling results.
186 To use unstripped libraries, check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle).
187
188 Here we use application [SimpleperfExampleWithNative](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative).
189 It builds an app-profiling.apk for profiling.
190
191 ```sh
192 $ git clone https://android.googlesource.com/platform/system/extras
193 $ cd extras/simpleperf/demo
194 # Open SimpleperfExamplesWithNative project with Android studio, and build this project
195 # successfully, otherwise the `./gradlew` command below will fail.
196 $ cd SimpleperfExampleWithNative
197
198 # On windows, use "gradlew" instead.
199 $ ./gradlew clean assemble
200 $ adb install -r app/build/outputs/apk/profiling/app-profiling.apk
201 ```
202
203 ### Record and report profiling data
204
205 We can use [app-profiler.py](#app_profiler-py) to profile Android applications.
206
207 ```sh
208 # Record perf.data.
209 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative
210 ```
211
212 This will collect profiling data in perf.data in the current directory, and related native
213 binaries in binary_cache/.
214
215 Normally we need to use the app when profiling, otherwise we may record no samples. But in this
216 case, the MainActivity starts a busy thread. So we don't need to use the app while profiling.
217
218 ```sh
219 # Report perf.data in stdio interface.
220 $ python report.py
221 Cmdline: /data/local/tmp/simpleperf record -e task-clock:u -g -f 1000 --duration 10 ...
222 Arch: arm64
223 Event: cpu-cycles:u (type 0, config 0)
224 Samples: 9966
225 Event count: 22661027577
226
227 Overhead Command Pid Tid Shared Object Symbol
228 59.69% amplewithnative 10440 10452 /system/lib64/libc.so strtol
229 8.60% amplewithnative 10440 10452 /system/lib64/libc.so isalpha
230 ...
231 ```
232
233 [report.py](#report-py) reports profiling data in stdio interface. If there are a lot of unknown
234 symbols in the report, check [here](#how-to-solve-missing-symbols-in-report).
235
236 ```sh
237 # Report perf.data in html interface.
238 $ python report_html.py
239
240 # Add source code and disassembly. Change the path of source_dirs if it not correct.
241 $ python report_html.py --add_source_code --source_dirs ../demo/SimpleperfExampleWithNative \
242 --add_disassembly
243 ```
244
245 [report_html.py](#report_html-py) generates report in report.html, and pops up a browser tab to
246 show it.
247
248 ### Record and report call graph
249
250 We can record and report [call graphs](#record-call-graphs-in-record-cmd) as below.
251
252 ```sh
253 # Record dwarf based call graphs: add "-g" in the -r option.
254 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative \
255 -r "-e task-clock:u -f 1000 --duration 10 -g"
256
257 # Record stack frame based call graphs: add "--call-graph fp" in the -r option.
258 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative \
259 -r "-e task-clock:u -f 1000 --duration 10 --call-graph fp"
260
261 # Report call graphs in stdio interface.
262 $ python report.py -g
263
264 # Report call graphs in python Tk interface.
265 $ python report.py -g --gui
266
267 # Report call graphs in html interface.
268 $ python report_html.py
269
270 # Report call graphs in flame graphs.
271 # On Windows, use inferno.bat instead of ./inferno.sh.
272 $ ./inferno.sh -sc
273 ```
274
275 ### Report in html interface
276
277 We can use [report_html.py](#report_html-py) to show profiling results in a web browser.
278 report_html.py integrates chart statistics, sample table, flame graphs, source code annotation
279 and disassembly annotation. It is the recommended way to show reports.
280
281 ```sh
282 $ python report_html.py
283 ```
284
285 ### Show flame graph
286
287 To show flame graphs, we need to first record call graphs. Flame graphs are shown by
288 report_html.py in the "Flamegraph" tab.
289 We can also use [inferno](#inferno) to show flame graphs directly.
290
291 ```sh
292 # On Windows, use inferno.bat instead of ./inferno.sh.
293 $ ./inferno.sh -sc
294 ```
295
296 We can also build flame graphs using https://github.com/brendangregg/FlameGraph.
297 Please make sure you have perl installed.
298
299 ```sh
300 $ git clone https://github.com/brendangregg/FlameGraph.git
301 $ python report_sample.py --symfs binary_cache >out.perf
302 $ FlameGraph/stackcollapse-perf.pl out.perf >out.folded
303 $ FlameGraph/flamegraph.pl out.folded >a.svg
304 ```
305
306 ### Record both on CPU time and off CPU time
307
308 We can [record both on CPU time and off CPU time](#record-both-on-cpu-time-and-off-cpu-time-in-record-cmd).
309
310 First check if trace-offcpu feature is supported on the device.
311
312 ```sh
313 $ python run_simpleperf_on_device.py list --show-features
314 dwarf-based-call-graph
315 trace-offcpu
316 ```
317
318 If trace-offcpu is supported, it will be shown in the feature list. Then we can try it.
319
320 ```sh
321 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .SleepActivity \
322 -r "-g -e task-clock:u -f 1000 --duration 10 --trace-offcpu"
323 $ python report_html.py --add_disassembly --add_source_code --source_dirs ../demo
324 ```
325
326 ### Profile from launch
327
328 We can [profile from launch of an application](#profile-from-launch-of-an-application).
329
330 ```sh
331 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .MainActivity \
332 --arch arm64 --profile_from_launch
333 ```
334
335 ### Parse profiling data manually
336
337 We can also write python scripts to parse profiling data manually, by using
338 [simpleperf_report_lib.py](#simpleperf_report_lib-py). Examples are report_sample.py,
339 report_html.py.
340
341 ## Executable commands reference
342
343 ### How does simpleperf work?
344
345 Modern CPUs have a hardware component called the performance monitoring unit (PMU). The PMU has
346 several hardware counters, counting events like how many cpu cycles have happened, how many
347 instructions have executed, or how many cache misses have happened.
348
349 The Linux kernel wraps these hardware counters into hardware perf events. In addition, the Linux
350 kernel also provides hardware independent software events and tracepoint events. The Linux kernel
351 exposes all events to userspace via the perf_event_open system call, which is used by simpleperf.
352
353 Simpleperf has three main commands: stat, record and report.
354
355 The stat command gives a summary of how many events have happened in the profiled processes in a
356 time period. Heres how it works:
357 1. Given user options, simpleperf enables profiling by making a system call to the kernel.
358 2. The kernel enables counters while the profiled processes are running.
359 3. After profiling, simpleperf reads counters from the kernel, and reports a counter summary.
360
361 The record command records samples of the profiled processes in a time period. Heres how it works:
362 1. Given user options, simpleperf enables profiling by making a system call to the kernel.
363 2. Simpleperf creates mapped buffers between simpleperf and the kernel.
364 3. The kernel enables counters while the profiled processes are running.
365 4. Each time a given number of events happen, the kernel dumps a sample to the mapped buffers.
366 5. Simpleperf reads samples from the mapped buffers and stores profiling data in a file called
367 perf.data.
368
369 The report command reads perf.data and any shared libraries used by the profiled processes,
370 and outputs a report showing where the time was spent.
371
372 ### Commands
373
374 Simpleperf supports several commands, listed below:
375
376 ```
377 The dump command: dumps content in perf.data, used for debugging simpleperf.
378 The help command: prints help information for other commands.
379 The kmem command: collects kernel memory allocation information (will be replaced by Python scripts).
380 The list command: lists all event types supported on the Android device.
381 The record command: profiles processes and stores profiling data in perf.data.
382 The report command: reports profiling data in perf.data.
383 The report-sample command: reports each sample in perf.data, used for supporting integration of
384 simpleperf in Android Studio.
385 The stat command: profiles processes and prints counter summary.
386 ```
387
388 Each command supports different options, which can be seen through help message.
389
390 ```sh
391 # List all commands.
392 $ simpleperf --help
393
394 # Print help message for record command.
395 $ simpleperf record --help
396 ```
397
398 Below describes the most frequently used commands, which are list, stat, record and report.
399
400 ### The list command
401
402 The list command lists all events available on the device. Different devices may support different
403 events because they have different hardware and kernels.
404
405 ```sh
406 $ simpleperf list
407 List of hw-cache events:
408 branch-loads
409 ...
410 List of hardware events:
411 cpu-cycles
412 instructions
413 ...
414 List of software events:
415 cpu-clock
416 task-clock
417 ...
418 ```
419
420 On ARM/ARM64, the list command also shows a list of raw events, they are the events supported by
421 the ARM PMU on the device. The kernel has wrapped part of them into hardware events and hw-cache
422 events. For example, raw-cpu-cycles is wrapped into cpu-cycles, raw-instruction-retired is wrapped
423 into instructions. The raw events are provided in case we want to use some events supported on the
424 device, but unfortunately not wrapped by the kernel.
425
426 ### The stat command
427
428 The stat command is used to get event counter values of the profiled processes. By passing options,
429 we can select which events to use, which processes/threads to monitor, how long to monitor and the
430 print interval.
431
432 ```sh
433 # Stat using default events (cpu-cycles,instructions,...), and monitor process 7394 for 10 seconds.
434 $ simpleperf stat -p 7394 --duration 10
435 Performance counter statistics:
436
437 1,320,496,145 cpu-cycles # 0.131736 GHz (100%)
438 510,426,028 instructions # 2.587047 cycles per instruction (100%)
439 4,692,338 branch-misses # 468.118 K/sec (100%)
440 886.008130(ms) task-clock # 0.088390 cpus used (100%)
441 753 context-switches # 75.121 /sec (100%)
442 870 page-faults # 86.793 /sec (100%)
443
444 Total test time: 10.023829 seconds.
445 ```
446
447 #### Select events to stat
448
449 We can select which events to use via -e.
450
451 ```sh
452 # Stat event cpu-cycles.
453 $ simpleperf stat -e cpu-cycles -p 11904 --duration 10
454
455 # Stat event cache-references and cache-misses.
456 $ simpleperf stat -e cache-references,cache-misses -p 11904 --duration 10
457 ```
458
459 When running the stat command, if the number of hardware events is larger than the number of
460 hardware counters available in the PMU, the kernel shares hardware counters between events, so each
461 event is only monitored for part of the total time. In the example below, there is a percentage at
462 the end of each row, showing the percentage of the total time that each event was actually
463 monitored.
464
465 ```sh
466 # Stat using event cache-references, cache-references:u,....
467 $ simpleperf stat -p 7394 -e cache-references,cache-references:u,cache-references:k \
468 -e cache-misses,cache-misses:u,cache-misses:k,instructions --duration 1
469 Performance counter statistics:
470
471 4,331,018 cache-references # 4.861 M/sec (87%)
472 3,064,089 cache-references:u # 3.439 M/sec (87%)
473 1,364,959 cache-references:k # 1.532 M/sec (87%)
474 91,721 cache-misses # 102.918 K/sec (87%)
475 45,735 cache-misses:u # 51.327 K/sec (87%)
476 38,447 cache-misses:k # 43.131 K/sec (87%)
477 9,688,515 instructions # 10.561 M/sec (89%)
478
479 Total test time: 1.026802 seconds.
480 ```
481
482 In the example above, each event is monitored about 87% of the total time. But there is no
483 guarantee that any pair of events are always monitored at the same time. If we want to have some
484 events monitored at the same time, we can use --group.
485
486 ```sh
487 # Stat using event cache-references, cache-references:u,....
488 $ simpleperf stat -p 7964 --group cache-references,cache-misses \
489 --group cache-references:u,cache-misses:u --group cache-references:k,cache-misses:k \
490 -e instructions --duration 1
491 Performance counter statistics:
492
493 3,638,900 cache-references # 4.786 M/sec (74%)
494 65,171 cache-misses # 1.790953% miss rate (74%)
495 2,390,433 cache-references:u # 3.153 M/sec (74%)
496 32,280 cache-misses:u # 1.350383% miss rate (74%)
497 879,035 cache-references:k # 1.251 M/sec (68%)
498 30,303 cache-misses:k # 3.447303% miss rate (68%)
499 8,921,161 instructions # 10.070 M/sec (86%)
500
501 Total test time: 1.029843 seconds.
502 ```
503
504 #### Select target to stat
505
506 We can select which processes or threads to monitor via -p or -t. Monitoring a
507 process is the same as monitoring all threads in the process. Simpleperf can also fork a child
508 process to run the new command and then monitor the child process.
509
510 ```sh
511 # Stat process 11904 and 11905.
512 $ simpleperf stat -p 11904,11905 --duration 10
513
514 # Stat thread 11904 and 11905.
515 $ simpleperf stat -t 11904,11905 --duration 10
516
517 # Start a child process running `ls`, and stat it.
518 $ simpleperf stat ls
519
520 # Stat a debuggable Android application.
521 $ simpleperf stat --app com.example.simpleperf.simpleperfexamplewithnative
522
523 # Stat system wide using -a.
524 $ simpleperf stat -a --duration 10
525 ```
526
527 #### Decide how long to stat
528
529 When monitoring existing threads, we can use --duration to decide how long to monitor. When
530 monitoring a child process running a new command, simpleperf monitors until the child process ends.
531 In this case, we can use Ctrl-C to stop monitoring at any time.
532
533 ```sh
534 # Stat process 11904 for 10 seconds.
535 $ simpleperf stat -p 11904 --duration 10
536
537 # Stat until the child process running `ls` finishes.
538 $ simpleperf stat ls
539
540 # Stop monitoring using Ctrl-C.
541 $ simpleperf stat -p 11904 --duration 10
542 ^C
543 ```
544
545 If you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM,
546 SIGHUP signals to simpleperf to stop monitoring.
547
548 #### Decide the print interval
549
550 When monitoring perf counters, we can also use --interval to decide the print interval.
551
552 ```sh
553 # Print stat for process 11904 every 300ms.
554 $ simpleperf stat -p 11904 --duration 10 --interval 300
555
556 # Print system wide stat at interval of 300ms for 10 seconds. Note that system wide profiling needs
557 # root privilege.
558 $ su 0 simpleperf stat -a --duration 10 --interval 300
559 ```
560
561 #### Display counters in systrace
562
563 Simpleperf can also work with systrace to dump counters in the collected trace. Below is an example
564 to do a system wide stat.
565
566 ```sh
567 # Capture instructions (kernel only) and cache misses with interval of 300 milliseconds for 15
568 # seconds.
569 $ su 0 simpleperf stat -e instructions:k,cache-misses -a --interval 300 --duration 15
570 # On host launch systrace to collect trace for 10 seconds.
571 (HOST)$ external/chromium-trace/systrace.py --time=10 -o new.html sched gfx view
572 # Open the collected new.html in browser and perf counters will be shown up.
573 ```
574
575 ### The record command
576
577 The record command is used to dump samples of the profiled processes. Each sample can contain
578 information like the time at which the sample was generated, the number of events since last
579 sample, the program counter of a thread, the call chain of a thread.
580
581 By passing options, we can select which events to use, which processes/threads to monitor,
582 what frequency to dump samples, how long to monitor, and where to store samples.
583
584 ```sh
585 # Record on process 7394 for 10 seconds, using default event (cpu-cycles), using default sample
586 # frequency (4000 samples per second), writing records to perf.data.
587 $ simpleperf record -p 7394 --duration 10
588 simpleperf I cmd_record.cpp:316] Samples recorded: 21430. Samples lost: 0.
589 ```
590
591 #### Select events to record
592
593 By default, the cpu-cycles event is used to evaluate consumed cpu cycles. But we can also use other
594 events via -e.
595
596 ```sh
597 # Record using event instructions.
598 $ simpleperf record -e instructions -p 11904 --duration 10
599
600 # Record using task-clock, which shows the passed CPU time in nanoseconds.
601 $ simpleperf record -e task-clock -p 11904 --duration 10
602 ```
603
604 #### Select target to record
605
606 The way to select target in record command is similar to that in the stat command.
607
608 ```sh
609 # Record process 11904 and 11905.
610 $ simpleperf record -p 11904,11905 --duration 10
611
612 # Record thread 11904 and 11905.
613 $ simpleperf record -t 11904,11905 --duration 10
614
615 # Record a child process running `ls`.
616 $ simpleperf record ls
617
618 # Record a debuggable Android application.
619 $ simpleperf record --app com.example.simpleperf.simpleperfexamplewithnative
620
621 # Record system wide.
622 $ simpleperf record -a --duration 10
623 ```
624
625 #### Set the frequency to record
626
627 We can set the frequency to dump records via -f or -c. For example, -f 4000 means
628 dumping approximately 4000 records every second when the monitored thread runs. If a monitored
629 thread runs 0.2s in one second (it can be preempted or blocked in other times), simpleperf dumps
630 about 4000 * 0.2 / 1.0 = 800 records every second. Another way is using -c. For example, -c 10000
631 means dumping one record whenever 10000 events happen.
632
633 ```sh
634 # Record with sample frequency 1000: sample 1000 times every second running.
635 $ simpleperf record -f 1000 -p 11904,11905 --duration 10
636
637 # Record with sample period 100000: sample 1 time every 100000 events.
638 $ simpleperf record -c 100000 -t 11904,11905 --duration 10
639 ```
640
641 #### Decide how long to record
642
643 The way to decide how long to monitor in record command is similar to that in the stat command.
644
645 ```sh
646 # Record process 11904 for 10 seconds.
647 $ simpleperf record -p 11904 --duration 10
648
649 # Record until the child process running `ls` finishes.
650 $ simpleperf record ls
651
652 # Stop monitoring using Ctrl-C.
653 $ simpleperf record -p 11904 --duration 10
654 ^C
655 ```
656
657 If you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM,
658 SIGHUP signals to simpleperf to stop monitoring.
659
660 #### Set the path to store profiling data
661
662 By default, simpleperf stores profiling data in perf.data in the current directory. But the path
663 can be changed using -o.
664
665 ```sh
666 # Write records to data/perf2.data.
667 $ simpleperf record -p 11904 -o data/perf2.data --duration 10
668 ```
669
670 <a name="record-call-graphs-in-record-cmd"></a>
671 #### Record call graphs
672
673 A call graph is a tree showing function call relations. Below is an example.
674
675 ```
676 main() {
677 FunctionOne();
678 FunctionTwo();
679 }
680 FunctionOne() {
681 FunctionTwo();
682 FunctionThree();
683 }
684 a call graph:
685 main-> FunctionOne
686 | |
687 | |-> FunctionTwo
688 | |-> FunctionThree
689 |
690 |-> FunctionTwo
691 ```
692
693 A call graph shows how a function calls other functions, and a reversed call graph shows how
694 a function is called by other functions. To show a call graph, we need to first record it, then
695 report it.
696
697 There are two ways to record a call graph, one is recording a dwarf based call graph, the other is
698 recording a stack frame based call graph. Recording dwarf based call graphs needs support of debug
699 information in native binaries. While recording stack frame based call graphs needs support of
700 stack frame registers.
701
702 ```sh
703 # Record a dwarf based call graph
704 $ simpleperf record -p 11904 -g --duration 10
705
706 # Record a stack frame based call graph
707 $ simpleperf record -p 11904 --call-graph fp --duration 10
708 ```
709
710 [Here](#suggestions-about-recording-call-graphs) are some suggestions about recording call graphs
711
712 <a name="record-both-on-cpu-time-and-off-cpu-time-in-record-cmd"></a>
713 #### Record both on CPU time and off CPU time
714
715 Simpleperf is a CPU profiler, it generates samples for a thread only when it is running on a CPU.
716 However, sometimes we want to figure out where the time of a thread is spent, whether it is running
717 on a CPU, or staying in the kernel's ready queue, or waiting for something like I/O events.
718
719 To support this, the record command uses --trace-offcpu to trace both on CPU time and off CPU time.
720 When --trace-offcpu is used, simpleperf generates a sample when a running thread is scheduled out,
721 so we know the callstack of a thread when it is scheduled out. And when reporting a perf.data
722 generated with --trace-offcpu, we use time to the next sample (instead of event counts from the
723 previous sample) as the weight of the current sample. As a result, we can get a call graph based
724 on timestamps, including both on CPU time and off CPU time.
725
726 trace-offcpu is implemented using sched:sched_switch tracepoint event, which may not be supported
727 on old kernels. But it is guaranteed to be supported on devices >= Android O MR1. We can check
728 whether trace-offcpu is supported as below.
729
730 ```sh
731 $ simpleperf list --show-features
732 dwarf-based-call-graph
733 trace-offcpu
734 ```
735
736 If trace-offcpu is supported, it will be shown in the feature list. Then we can try it.
737
738 ```sh
739 # Record with --trace-offcpu.
740 $ simpleperf record -g -p 11904 --duration 10 --trace-offcpu
741
742 # Record with --trace-offcpu using app_profiler.py.
743 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .SleepActivity \
744 -r "-g -e task-clock:u -f 1000 --duration 10 --trace-offcpu"
745 ```
746
747 Below is an example comparing the profiling result with / without --trace-offcpu.
748 First we record without --trace-offcpu.
749
750 ```sh
751 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .SleepActivity
752
753 $ python report_html.py --add_disassembly --add_source_code --source_dirs ../demo
754 ```
755
756 The result is [here](./without_trace_offcpu.html).
757 In the result, all time is taken by RunFunction(), and sleep time is ignored.
758 But if we add --trace-offcpu, the result changes.
759
760 ```sh
761 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .SleepActivity \
762 -r "-g -e task-clock:u --trace-offcpu -f 1000 --duration 10"
763
764 $ python report_html.py --add_disassembly --add_source_code --source_dirs ../demo
765 ```
766
767 The result is [here](./trace_offcpu.html).
768 In the result, half of the time is taken by RunFunction(), and the other half is taken by
769 SleepFunction(). So it traces both on CPU time and off CPU time.
770
771 ### The report command
772
773 The report command is used to report profiling data generated by the record command. The report
774 contains a table of sample entries. Each sample entry is a row in the report. The report command
775 groups samples belong to the same process, thread, library, function in the same sample entry. Then
776 sort the sample entries based on the event count a sample entry has.
777
778 By passing options, we can decide how to filter out uninteresting samples, how to group samples
779 into sample entries, and where to find profiling data and binaries.
780
781 Below is an example. Records are grouped into 4 sample entries, each entry is a row. There are
782 several columns, each column shows piece of information belonging to a sample entry. The first
783 column is Overhead, which shows the percentage of events inside the current sample entry in total
784 events. As the perf event is cpu-cycles, the overhead is the percentage of CPU cycles used in each
785 function.
786
787 ```sh
788 # Reports perf.data, using only records sampled in libsudo-game-jni.so, grouping records using
789 # thread name(comm), process id(pid), thread id(tid), function name(symbol), and showing sample
790 # count for each row.
791 $ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so \
792 --sort comm,pid,tid,symbol -n
793 Cmdline: /data/data/com.example.sudogame/simpleperf record -p 7394 --duration 10
794 Arch: arm64
795 Event: cpu-cycles (type 0, config 0)
796 Samples: 28235
797 Event count: 546356211
798
799 Overhead Sample Command Pid Tid Symbol
800 59.25% 16680 sudogame 7394 7394 checkValid(Board const&, int, int)
801 20.42% 5620 sudogame 7394 7394 canFindSolution_r(Board&, int, int)
802 13.82% 4088 sudogame 7394 7394 randomBlock_r(Board&, int, int, int, int, int)
803 6.24% 1756 sudogame 7394 7394 @plt
804 ```
805
806 #### Set the path to read profiling data
807
808 By default, the report command reads profiling data from perf.data in the current directory.
809 But the path can be changed using -i.
810
811 ```sh
812 $ simpleperf report -i data/perf2.data
813 ```
814
815 #### Set the path to find binaries
816
817 To report function symbols, simpleperf needs to read executable binaries used by the monitored
818 processes to get symbol table and debug information. By default, the paths are the executable
819 binaries used by monitored processes while recording. However, these binaries may not exist when
820 reporting or not contain symbol table and debug information. So we can use --symfs to redirect
821 the paths.
822
823 ```sh
824 # In this case, when simpleperf wants to read executable binary /A/b, it reads file in /A/b.
825 $ simpleperf report
826
827 # In this case, when simpleperf wants to read executable binary /A/b, it prefers file in
828 # /debug_dir/A/b to file in /A/b.
829 $ simpleperf report --symfs /debug_dir
830 ```
831
832 #### Filter samples
833
834 When reporting, it happens that not all records are of interest. The report command supports four
835 filters to select samples of interest.
836
837 ```sh
838 # Report records in threads having name sudogame.
839 $ simpleperf report --comms sudogame
840
841 # Report records in process 7394 or 7395
842 $ simpleperf report --pids 7394,7395
843
844 # Report records in thread 7394 or 7395.
845 $ simpleperf report --tids 7394,7395
846
847 # Report records in libsudo-game-jni.so.
848 $ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so
849 ```
850
851 #### Group samples into sample entries
852
853 The report command uses --sort to decide how to group sample entries.
854
855 ```sh
856 # Group records based on their process id: records having the same process id are in the same
857 # sample entry.
858 $ simpleperf report --sort pid
859
860 # Group records based on their thread id and thread comm: records having the same thread id and
861 # thread name are in the same sample entry.
862 $ simpleperf report --sort tid,comm
863
864 # Group records based on their binary and function: records in the same binary and function are in
865 # the same sample entry.
866 $ simpleperf report --sort dso,symbol
867
868 # Default option: --sort comm,pid,tid,dso,symbol. Group records in the same thread, and belong to
869 # the same function in the same binary.
870 $ simpleperf report
871 ```
872
873 <a name="report-call-graphs-in-report-cmd"></a>
874 #### Report call graphs
875
876 To report a call graph, please make sure the profiling data is recorded with call graphs,
877 as [here](#record-call-graphs-in-record-cmd).
878
879 ```
880 $ simpleperf report -g
881 ```
882
883 ## Scripts reference
884
885 <a name="app_profiler-py"></a>
886 ### app_profiler.py
887
888 app_profiler.py is used to record profiling data for Android applications and native executables.
889
890 ```sh
891 # Record an Android application.
892 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative
893
894 # Record an Android application without compiling the Java code into native instructions.
895 # Used when you only profile the C++ code, or the Java code has already been compiled into native
896 # instructions.
897 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -nc
898
899 # Record running a specific activity of an Android application.
900 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .SleepActivity
901
902 # Record a native process.
903 $ python app_profiler.py -np surfaceflinger
904
905 # Record a command.
906 $ python app_profiler.py -cmd \
907 "dex2oat --dex-file=/data/local/tmp/app-profiling.apk --oat-file=/data/local/tmp/a.oat" \
908 --arch arm
909
910 # Record an Android application, and use -r to send custom options to the record command.
911 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative \
912 -r "-e cpu-clock -g --duration 30"
913
914 # Record both on CPU time and off CPU time.
915 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative \
916 -r "-e task-clock -g -f 1000 --duration 10 --trace-offcpu"
917
918 # Profile activity startup time using --profile_from_launch.
919 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative \
920 --profile_from_launch --arch arm64
921 ```
922
923 #### Profile from launch of an application
924
925 Sometimes we want to profile the launch-time of an application. To support this, we added --app in
926 the record command. The --app option sets the package name of the Android application to profile.
927 If the app is not already running, the record command will poll for the app process in a loop with
928 an interval of 1ms. So to profile from launch of an application, we can first start the record
929 command with --app, then start the app. Below is an example.
930
931 ```sh
932 $ python run_simpleperf_on_device.py record
933 --app com.example.simpleperf.simpleperfexamplewithnative \
934 -g --duration 1 -o /data/local/tmp/perf.data
935 # Start the app manually or using the `am` command.
936 ```
937
938 To make it convenient to use, app_profiler.py combines these in the --profile_from_launch option.
939
940 ```sh
941 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative -a .MainActivity \
942 --arch arm64 --profile_from_launch
943 ```
944
945 <a name="binary_cache_builder-py"></a>
946 ### binary_cache_builder.py
947
948 The binary_cache directory is a directory holding binaries needed by a profiling data file. The
949 binaries are expected to be unstripped, having debug information and symbol tables. The
950 binary_cache directory is used by report scripts to read symbols of binaries. It is also used by
951 report_html.py to generate annotated source code and disassembly.
952
953 By default, app_profiler.py builds the binary_cache directory after recording. But we can also
954 build binary_cache for existing profiling data files using binary_cache_builder.py. It is useful
955 when you record profiling data using `simpleperf record` directly, to do system wide profiling or
956 record without usb cable connected.
957
958 binary_cache_builder.py can either pull binaries from an Android device, or find binaries in
959 directories on the host (via -lib).
960
961 ```sh
962 # Generate binary_cache for perf.data, by pulling binaries from the device.
963 $ python binary_cache_builder.py
964
965 # Generate binary_cache, by pulling binaries from the device and finding binaries in ../demo.
966 $ python binary_cache_builder.py -lib ../demo
967 ```
968
969 <a name="run_simpleperf_on_device-py"></a>
970 ### run_simpleperf_on_device.py
971
972 This script pushes the simpleperf executable on the device, and run a simpleperf command on the
973 device. It is more convenient than running adb commands manually.
974
975 <a name="report-py"></a>
976 ### report.py
977
978 report.py is a wrapper of the report command on the host. It accepts all options of the report
979 command.
980
981 ```sh
982 # Report call graph
983 $ python report.py -g
984
985 # Report call graph in a GUI window implemented by Python Tk.
986 $ python report.py -g --gui
987 ```
988
989 <a name="report_html-py"></a>
990 ### report_html.py
991
992 report_html.py generates report.html based on the profiling data. Then the report.html can show
993 the profiling result without depending on other files. So it can be shown in local browsers or
994 passed to other machines. Depending on which command-line options are used, the content of the
995 report.html can include: chart statistics, sample table, flame graphs, annotated source code for
996 each function, annotated disassembly for each function.
997
998 ```sh
999 # Generate chart statistics, sample table and flame graphs, based on perf.data.
1000 $ python report_html.py
1001
1002 # Add source code.
1003 $ python report_html.py --add_source_code --source_dirs ../demo/SimpleperfExampleWithNative
1004
1005 # Add disassembly.
1006 $ python report_html.py --add_disassembly
1007 ```
1008
1009 Below is an example of generating html profiling results for SimpleperfExampleWithNative.
1010
1011 ```sh
1012 $ python app_profiler.py -p com.example.simpleperf.simpleperfexamplewithnative
1013 $ python report_html.py --add_source_code --source_dirs ../demo --add_disassembly
1014 ```
1015
1016 After opening the generated [report.html](./report_html.html) in a browser, there are several tabs:
1017
1018 The first tab is "Chart Statistics". You can click the pie chart to show the time consumed by each
1019 process, thread, library and function.
1020
1021 The second tab is "Sample Table". It shows the time taken by each function. By clicking one row in
1022 the table, we can jump to a new tab called "Function".
1023
1024 The third tab is "Flamegraph". It shows the flame graphs generated by [inferno](./inferno.md).
1025
1026 The fourth tab is "Function". It only appears when users click a row in the "Sample Table" tab.
1027 It shows information of a function, including:
1028
1029 1. A flame graph showing functions called by that function.
1030 2. A flame graph showing functions calling that function.
1031 3. Annotated source code of that function. It only appears when there are source code files for
1032 that function.
1033 4. Annotated disassembly of that function. It only appears when there are binaries containing that
1034 function.
1035
1036 ### inferno
1037
1038 [inferno](./inferno.md) is a tool used to generate flame graph in a html file.
1039
1040 ```sh
1041 # Generate flame graph based on perf.data.
1042 # On Windows, use inferno.bat instead of ./inferno.sh.
1043 $ ./inferno.sh -sc --record_file perf.data
1044
1045 # Record a native program and generate flame graph.
1046 $ ./inferno.sh -np surfaceflinger
1047 ```
1048
1049 <a name="pprof_proto_generator-py"></a>
1050 ### pprof_proto_generator.py
1051
1052 It converts a profiling data file into pprof.proto, a format used by [pprof](https://github.com/google/pprof).
1053
1054 ```sh
1055 # Convert perf.data in the current directory to pprof.proto format.
1056 $ python pprof_proto_generator.py
1057 $ pprof -pdf pprof.profile
1058 ```
1059
1060 <a name="report_sample-py"></a>
1061 ### report_sample.py
1062
1063 It converts a profiling data file into a format used by [FlameGraph](https://github.com/brendangregg/FlameGraph).
1064
1065 ```sh
1066 # Convert perf.data in the current directory to a format used by FlameGraph.
1067 $ python report_sample.py --symfs binary_cache >out.perf
1068 $ git clone https://github.com/brendangregg/FlameGraph.git
1069 $ FlameGraph/stackcollapse-perf.pl out.perf >out.folded
1070 $ FlameGraph/flamegraph.pl out.folded >a.svg
1071 ```
1072
1073 <a name="simpleperf_report_lib-py"></a>
1074 ### simpleperf_report_lib.py
1075
1076 simpleperf_report_lib.py is a Python library used to parse profiling data files generated by the
1077 record command. Internally, it uses libsimpleperf_report.so to do the work. Generally, for each
1078 profiling data file, we create an instance of ReportLib, pass it the file path (via SetRecordFile).
1079 Then we can read all samples through GetNextSample(). For each sample, we can read its event info
1080 (via GetEventOfCurrentSample), symbol info (via GetSymbolOfCurrentSample) and call chain info
1081 (via GetCallChainOfCurrentSample). We can also get some global information, like record options
1082 (via GetRecordCmd), the arch of the device (via GetArch) and meta strings (via MetaInfo).
1083
1084 Examples of using simpleperf_report_lib.py are in report_sample.py, report_html.py,
1085 pprof_proto_generator.py and inferno/inferno.py.
1086
1087 ## Answers to common issues
1088
1089 ### Why we suggest profiling on Android >= N devices?
1090 ```
1091 1. Running on a device reflects a real running situation, so we suggest
1092 profiling on real devices instead of emulators.
1093 2. To profile Java code, we need ART running in oat mode, which is only
1094 available >= L for rooted devices, and >= N for non-rooted devices.
1095 3. Old Android versions are likely to be shipped with old kernels (< 3.18),
1096 which may not support profiling features like recording dwarf based call graphs.
1097 4. Old Android versions are likely to be shipped with Arm32 chips. In Arm32
1098 mode, recording stack frame based call graphs doesn't work well.
1099 ```
1100
1101 ### Suggestions about recording call graphs
1102
1103 Below is our experiences of dwarf based call graphs and stack frame based call graphs.
1104
1105 dwarf based call graphs:
1106 1. Need support of debug information in binaries.
1107 2. Behave normally well on both ARM and ARM64, for both fully compiled Java code and C++ code.
1108 3. Can only unwind 64K stack for each sample. So usually can't show complete flame-graph. But
1109 probably is enough for users to identify hot places.
1110 4. Take more CPU time than stack frame based call graphs. So the sample frequency is suggested
1111 to be 1000 Hz. Thus at most 1000 samples per second.
1112
1113 stack frame based call graphs:
1114 1. Need support of stack frame registers.
1115 2. Don't work well on ARM. Because ARM is short of registers, and ARM and THUMB code have different
1116 stack frame registers. So the kernel can't unwind user stack containing both ARM/THUMB code.
1117 3. Also don't work well on fully compiled Java code on ARM64. Because the ART compiler doesn't
1118 reserve stack frame registers.
1119 4. Work well when profiling native programs on ARM64. One example is profiling surfacelinger. And
1120 usually shows complete flame-graph when it works well.
1121 5. Take less CPU time than dwarf based call graphs. So the sample frequency can be 4000 Hz or
1122 higher.
1123
1124 So if you need to profile code on ARM or profile fully compiled Java code, dwarf based call graphs
1125 may be better. If you need to profile C++ code on ARM64, stack frame based call graphs may be
1126 better. After all, you can always try dwarf based call graph first, because it always produces
1127 reasonable results when given unstripped binaries properly. If it doesn't work well enough, then
1128 try stack frame based call graphs instead.
1129
1130 Simpleperf needs to have unstripped native binaries on the device to generate good dwarf based call
1131 graphs. It can be supported in two ways:
1132 1. Use unstripped native binaries when building the apk, as [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle).
1133 2. Pass directory containing unstripped native libraries to app_profiler.py via -lib. And it will
1134 download the unstripped native libraries on the device.
1135
1136 ```sh
1137 $ python app_profiler.py -lib NATIVE_LIB_DIR
1138 ```
1139
1140 ### How to solve missing symbols in report?
1141
1142 The simpleperf record command collects symbols on device in perf.data. But if the native libraries
1143 you use on device are stripped, this will result in a lot of unknown symbols in the report. A
1144 solution is to build binary_cache on host.
1145
1146 ```sh
1147 # Collect binaries needed by perf.data in binary_cache/.
1148 $ python binary_cache_builder.py -lib NATIVE_LIB_DIR,...
1149 ```
1150
1151 The NATIVE_LIB_DIRs passed in -lib option are the directories containing unstripped native
1152 libraries on host. After running it, the native libraries containing symbol tables are collected
1153 in binary_cache/ for use when reporting.
1154
1155 ```sh
1156 $ python report.py --symfs binary_cache
1157
1158 # report_html.py searches binary_cache/ automatically, so you don't need to
1159 # pass it any argument.
1160 $ python report_html.py
1161 ```