1# Simpleperf 2 3Simpleperf is a native profiling tool for Android. It can be used to profile 4both Android applications and native processes running on Android. It can 5profile both Java and C++ code on Android. It can be used on Android L 6and above. 7 8Simpleperf is part of the Android Open Source Project. The source code is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/). 9The latest document is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/doc/README.md). 10Bugs 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 68Simpleperf contains two parts: the simpleperf executable and Python scripts. 69 70The simpleperf executable works similar to linux-tools-perf, but has some specific features for 71the Android profiling environment: 72 731. 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 772. 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 823. 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 914. 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 99Detailed documentation for the simpleperf executable is [here](#executable-commands-reference). 100 101Python scripts are split into three parts according to their functions: 102 1031. Scripts used for simplifying recording, like app_profiler.py. 104 1052. Scripts used for reporting, like report.py, report_html.py, inferno. 106 1073. Scripts used for parsing profiling data, like simpleperf_report_lib.py. 108 109Detailed documentation for the Python scripts is [here](#scripts-reference). 110 111## Tools in simpleperf 112 113The simpleperf executables and Python scripts are located in simpleperf/ in ndk releases, and in 114system/extras/simpleperf/scripts/ in AOSP. Their functions are listed below. 115 116bin/: contains executables and shared libraries. 117 118bin/android/${arch}/simpleperf: static simpleperf executables used on the device. 119 120bin/${host}/${arch}/simpleperf: simpleperf executables used on the host, only supports reporting. 121 122bin/${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 134inferno/: 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 146This section shows how to profile an Android application. 147Some examples are [Here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/README.md). 148 149Simpleperf only supports profiling native instructions in binaries in ELF format. If the Java code 150is executed by interpreter, or with jit cache, it can’t be profiled by simpleperf. As Android 151supports Ahead-of-time compilation, it can compile Java bytecode into native instructions with 152debug information. On devices with Android version <= M, we need root privilege to compile Java 153bytecode with debug information. However, on devices with Android version >= N, we don't need 154root privilege to do so. 155 156Profiling an Android application involves three steps: 1571. Prepare the application. 1582. Record profiling data. 1593. Report profiling data. 160 161### Prepare an Android application 162 163Before profiling, we need to install the application on Android device. To get valid profiling 164results, please check following items: 165 1661. The application should be debuggable. 167Security 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 169the debug build type instead of the release build type. 170 1712. Run on an Android >= N device. 172[We suggest profiling on an Android >= N device](#why-we-suggest-profiling-on-android-n-devices). 173 1743. On Android O, add `wrap.sh` in the apk. 175To profile Java code, we need ART running in oat mode. But on Android O, debuggable applications 176are forced to run in jit mode. To work around this, we need to add a `wrap.sh` in the apk. So if 177you 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 1794. Make sure C++ code is compiled with optimizing flags. 180If the application contains C++ code, it can be compiled with -O0 flag in debug build type. 181This makes C++ code slow, to avoid that, check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle). 182 1835. Use native libraries with debug info in the apk when possible. 184If the application contains C++ code or pre-compiled native libraries, try to use unstripped 185libraries in the apk. This helps simpleperf generating better profiling results. 186To use unstripped libraries, check [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle). 187 188Here we use application [SimpleperfExampleWithNative](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative). 189It 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 205We 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 212This will collect profiling data in perf.data in the current directory, and related native 213binaries in binary_cache/. 214 215Normally we need to use the app when profiling, otherwise we may record no samples. But in this 216case, 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 221Cmdline: /data/local/tmp/simpleperf record -e task-clock:u -g -f 1000 --duration 10 ... 222Arch: arm64 223Event: cpu-cycles:u (type 0, config 0) 224Samples: 9966 225Event count: 22661027577 226 227Overhead Command Pid Tid Shared Object Symbol 22859.69% amplewithnative 10440 10452 /system/lib64/libc.so strtol 2298.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 234symbols 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 246show it. 247 248### Record and report call graph 249 250We 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 277We can use [report_html.py](#report_html-py) to show profiling results in a web browser. 278report_html.py integrates chart statistics, sample table, flame graphs, source code annotation 279and 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 287To show flame graphs, we need to first record call graphs. Flame graphs are shown by 288report_html.py in the "Flamegraph" tab. 289We 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 296We can also build flame graphs using https://github.com/brendangregg/FlameGraph. 297Please 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 308We can [record both on CPU time and off CPU time](#record-both-on-cpu-time-and-off-cpu-time-in-record-cmd). 309 310First check if trace-offcpu feature is supported on the device. 311 312```sh 313$ python run_simpleperf_on_device.py list --show-features 314dwarf-based-call-graph 315trace-offcpu 316``` 317 318If 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 328We 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 337We 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, 339report_html.py. 340 341## Executable commands reference 342 343### How does simpleperf work? 344 345Modern CPUs have a hardware component called the performance monitoring unit (PMU). The PMU has 346several hardware counters, counting events like how many cpu cycles have happened, how many 347instructions have executed, or how many cache misses have happened. 348 349The Linux kernel wraps these hardware counters into hardware perf events. In addition, the Linux 350kernel also provides hardware independent software events and tracepoint events. The Linux kernel 351exposes all events to userspace via the perf_event_open system call, which is used by simpleperf. 352 353Simpleperf has three main commands: stat, record and report. 354 355The stat command gives a summary of how many events have happened in the profiled processes in a 356time period. Here’s how it works: 3571. Given user options, simpleperf enables profiling by making a system call to the kernel. 3582. The kernel enables counters while the profiled processes are running. 3593. After profiling, simpleperf reads counters from the kernel, and reports a counter summary. 360 361The record command records samples of the profiled processes in a time period. Here’s how it works: 3621. Given user options, simpleperf enables profiling by making a system call to the kernel. 3632. Simpleperf creates mapped buffers between simpleperf and the kernel. 3643. The kernel enables counters while the profiled processes are running. 3654. Each time a given number of events happen, the kernel dumps a sample to the mapped buffers. 3665. Simpleperf reads samples from the mapped buffers and stores profiling data in a file called 367 perf.data. 368 369The report command reads perf.data and any shared libraries used by the profiled processes, 370and outputs a report showing where the time was spent. 371 372### Commands 373 374Simpleperf supports several commands, listed below: 375 376``` 377The dump command: dumps content in perf.data, used for debugging simpleperf. 378The help command: prints help information for other commands. 379The kmem command: collects kernel memory allocation information (will be replaced by Python scripts). 380The list command: lists all event types supported on the Android device. 381The record command: profiles processes and stores profiling data in perf.data. 382The report command: reports profiling data in perf.data. 383The report-sample command: reports each sample in perf.data, used for supporting integration of 384 simpleperf in Android Studio. 385The stat command: profiles processes and prints counter summary. 386``` 387 388Each 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 398Below describes the most frequently used commands, which are list, stat, record and report. 399 400### The list command 401 402The list command lists all events available on the device. Different devices may support different 403events because they have different hardware and kernels. 404 405```sh 406$ simpleperf list 407List of hw-cache events: 408 branch-loads 409 ... 410List of hardware events: 411 cpu-cycles 412 instructions 413 ... 414List of software events: 415 cpu-clock 416 task-clock 417 ... 418``` 419 420On ARM/ARM64, the list command also shows a list of raw events, they are the events supported by 421the ARM PMU on the device. The kernel has wrapped part of them into hardware events and hw-cache 422events. For example, raw-cpu-cycles is wrapped into cpu-cycles, raw-instruction-retired is wrapped 423into instructions. The raw events are provided in case we want to use some events supported on the 424device, but unfortunately not wrapped by the kernel. 425 426### The stat command 427 428The stat command is used to get event counter values of the profiled processes. By passing options, 429we can select which events to use, which processes/threads to monitor, how long to monitor and the 430print 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 435Performance 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%) 440886.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 444Total test time: 10.023829 seconds. 445``` 446 447#### Select events to stat 448 449We 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 459When running the stat command, if the number of hardware events is larger than the number of 460hardware counters available in the PMU, the kernel shares hardware counters between events, so each 461event is only monitored for part of the total time. In the example below, there is a percentage at 462the end of each row, showing the percentage of the total time that each event was actually 463monitored. 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 469Performance counter statistics: 470 4714,331,018 cache-references # 4.861 M/sec (87%) 4723,064,089 cache-references:u # 3.439 M/sec (87%) 4731,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%) 4779,688,515 instructions # 10.561 M/sec (89%) 478 479Total test time: 1.026802 seconds. 480``` 481 482In the example above, each event is monitored about 87% of the total time. But there is no 483guarantee that any pair of events are always monitored at the same time. If we want to have some 484events 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 491Performance counter statistics: 492 4933,638,900 cache-references # 4.786 M/sec (74%) 494 65,171 cache-misses # 1.790953% miss rate (74%) 4952,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%) 4998,921,161 instructions # 10.070 M/sec (86%) 500 501Total test time: 1.029843 seconds. 502``` 503 504#### Select target to stat 505 506We can select which processes or threads to monitor via -p or -t. Monitoring a 507process is the same as monitoring all threads in the process. Simpleperf can also fork a child 508process 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 529When monitoring existing threads, we can use --duration to decide how long to monitor. When 530monitoring a child process running a new command, simpleperf monitors until the child process ends. 531In 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 545If you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM, 546SIGHUP signals to simpleperf to stop monitoring. 547 548#### Decide the print interval 549 550When 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 563Simpleperf can also work with systrace to dump counters in the collected trace. Below is an example 564to 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 577The record command is used to dump samples of the profiled processes. Each sample can contain 578information like the time at which the sample was generated, the number of events since last 579sample, the program counter of a thread, the call chain of a thread. 580 581By passing options, we can select which events to use, which processes/threads to monitor, 582what 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 588simpleperf I cmd_record.cpp:316] Samples recorded: 21430. Samples lost: 0. 589``` 590 591#### Select events to record 592 593By default, the cpu-cycles event is used to evaluate consumed cpu cycles. But we can also use other 594events 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 606The 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 627We can set the frequency to dump records via -f or -c. For example, -f 4000 means 628dumping approximately 4000 records every second when the monitored thread runs. If a monitored 629thread runs 0.2s in one second (it can be preempted or blocked in other times), simpleperf dumps 630about 4000 * 0.2 / 1.0 = 800 records every second. Another way is using -c. For example, -c 10000 631means 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 643The 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 657If you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM, 658SIGHUP signals to simpleperf to stop monitoring. 659 660#### Set the path to store profiling data 661 662By default, simpleperf stores profiling data in perf.data in the current directory. But the path 663can 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 673A call graph is a tree showing function call relations. Below is an example. 674 675``` 676main() { 677 FunctionOne(); 678 FunctionTwo(); 679} 680FunctionOne() { 681 FunctionTwo(); 682 FunctionThree(); 683} 684a call graph: 685 main-> FunctionOne 686 | | 687 | |-> FunctionTwo 688 | |-> FunctionThree 689 | 690 |-> FunctionTwo 691``` 692 693A call graph shows how a function calls other functions, and a reversed call graph shows how 694a function is called by other functions. To show a call graph, we need to first record it, then 695report it. 696 697There are two ways to record a call graph, one is recording a dwarf based call graph, the other is 698recording a stack frame based call graph. Recording dwarf based call graphs needs support of debug 699information in native binaries. While recording stack frame based call graphs needs support of 700stack 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 715Simpleperf is a CPU profiler, it generates samples for a thread only when it is running on a CPU. 716However, sometimes we want to figure out where the time of a thread is spent, whether it is running 717on a CPU, or staying in the kernel's ready queue, or waiting for something like I/O events. 718 719To support this, the record command uses --trace-offcpu to trace both on CPU time and off CPU time. 720When --trace-offcpu is used, simpleperf generates a sample when a running thread is scheduled out, 721so we know the callstack of a thread when it is scheduled out. And when reporting a perf.data 722generated with --trace-offcpu, we use time to the next sample (instead of event counts from the 723previous sample) as the weight of the current sample. As a result, we can get a call graph based 724on timestamps, including both on CPU time and off CPU time. 725 726trace-offcpu is implemented using sched:sched_switch tracepoint event, which may not be supported 727on old kernels. But it is guaranteed to be supported on devices >= Android O MR1. We can check 728whether trace-offcpu is supported as below. 729 730```sh 731$ simpleperf list --show-features 732dwarf-based-call-graph 733trace-offcpu 734``` 735 736If 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 747Below is an example comparing the profiling result with / without --trace-offcpu. 748First 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 756The result is [here](./without_trace_offcpu.html). 757In the result, all time is taken by RunFunction(), and sleep time is ignored. 758But 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 767The result is [here](./trace_offcpu.html). 768In the result, half of the time is taken by RunFunction(), and the other half is taken by 769SleepFunction(). So it traces both on CPU time and off CPU time. 770 771### The report command 772 773The report command is used to report profiling data generated by the record command. The report 774contains a table of sample entries. Each sample entry is a row in the report. The report command 775groups samples belong to the same process, thread, library, function in the same sample entry. Then 776sort the sample entries based on the event count a sample entry has. 777 778By passing options, we can decide how to filter out uninteresting samples, how to group samples 779into sample entries, and where to find profiling data and binaries. 780 781Below is an example. Records are grouped into 4 sample entries, each entry is a row. There are 782several columns, each column shows piece of information belonging to a sample entry. The first 783column is Overhead, which shows the percentage of events inside the current sample entry in total 784events. As the perf event is cpu-cycles, the overhead is the percentage of CPU cycles used in each 785function. 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 793Cmdline: /data/data/com.example.sudogame/simpleperf record -p 7394 --duration 10 794Arch: arm64 795Event: cpu-cycles (type 0, config 0) 796Samples: 28235 797Event count: 546356211 798 799Overhead Sample Command Pid Tid Symbol 80059.25% 16680 sudogame 7394 7394 checkValid(Board const&, int, int) 80120.42% 5620 sudogame 7394 7394 canFindSolution_r(Board&, int, int) 80213.82% 4088 sudogame 7394 7394 randomBlock_r(Board&, int, int, int, int, int) 8036.24% 1756 sudogame 7394 7394 @plt 804``` 805 806#### Set the path to read profiling data 807 808By default, the report command reads profiling data from perf.data in the current directory. 809But 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 817To report function symbols, simpleperf needs to read executable binaries used by the monitored 818processes to get symbol table and debug information. By default, the paths are the executable 819binaries used by monitored processes while recording. However, these binaries may not exist when 820reporting or not contain symbol table and debug information. So we can use --symfs to redirect 821the 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 834When reporting, it happens that not all records are of interest. The report command supports four 835filters 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 853The 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 876To report a call graph, please make sure the profiling data is recorded with call graphs, 877as [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 888app_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 925Sometimes we want to profile the launch-time of an application. To support this, we added --app in 926the record command. The --app option sets the package name of the Android application to profile. 927If the app is not already running, the record command will poll for the app process in a loop with 928an interval of 1ms. So to profile from launch of an application, we can first start the record 929command 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 938To 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 948The binary_cache directory is a directory holding binaries needed by a profiling data file. The 949binaries are expected to be unstripped, having debug information and symbol tables. The 950binary_cache directory is used by report scripts to read symbols of binaries. It is also used by 951report_html.py to generate annotated source code and disassembly. 952 953By default, app_profiler.py builds the binary_cache directory after recording. But we can also 954build binary_cache for existing profiling data files using binary_cache_builder.py. It is useful 955when you record profiling data using `simpleperf record` directly, to do system wide profiling or 956record without usb cable connected. 957 958binary_cache_builder.py can either pull binaries from an Android device, or find binaries in 959directories 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 972This script pushes the simpleperf executable on the device, and run a simpleperf command on the 973device. It is more convenient than running adb commands manually. 974 975<a name="report-py"></a> 976### report.py 977 978report.py is a wrapper of the report command on the host. It accepts all options of the report 979command. 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 992report_html.py generates report.html based on the profiling data. Then the report.html can show 993the profiling result without depending on other files. So it can be shown in local browsers or 994passed to other machines. Depending on which command-line options are used, the content of the 995report.html can include: chart statistics, sample table, flame graphs, annotated source code for 996each 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 1009Below 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 1016After opening the generated [report.html](./report_html.html) in a browser, there are several tabs: 1017 1018The first tab is "Chart Statistics". You can click the pie chart to show the time consumed by each 1019process, thread, library and function. 1020 1021The second tab is "Sample Table". It shows the time taken by each function. By clicking one row in 1022the table, we can jump to a new tab called "Function". 1023 1024The third tab is "Flamegraph". It shows the flame graphs generated by [inferno](./inferno.md). 1025 1026The fourth tab is "Function". It only appears when users click a row in the "Sample Table" tab. 1027It shows information of a function, including: 1028 10291. A flame graph showing functions called by that function. 10302. A flame graph showing functions calling that function. 10313. Annotated source code of that function. It only appears when there are source code files for 1032 that function. 10334. 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 1052It 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 1063It 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 1076simpleperf_report_lib.py is a Python library used to parse profiling data files generated by the 1077record command. Internally, it uses libsimpleperf_report.so to do the work. Generally, for each 1078profiling data file, we create an instance of ReportLib, pass it the file path (via SetRecordFile). 1079Then 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 1084Examples of using simpleperf_report_lib.py are in report_sample.py, report_html.py, 1085pprof_proto_generator.py and inferno/inferno.py. 1086 1087## Answers to common issues 1088 1089### Why we suggest profiling on Android >= N devices? 1090``` 10911. Running on a device reflects a real running situation, so we suggest 1092profiling on real devices instead of emulators. 10932. To profile Java code, we need ART running in oat mode, which is only 1094available >= L for rooted devices, and >= N for non-rooted devices. 10953. Old Android versions are likely to be shipped with old kernels (< 3.18), 1096which may not support profiling features like recording dwarf based call graphs. 10974. Old Android versions are likely to be shipped with Arm32 chips. In Arm32 1098mode, recording stack frame based call graphs doesn't work well. 1099``` 1100 1101### Suggestions about recording call graphs 1102 1103Below is our experiences of dwarf based call graphs and stack frame based call graphs. 1104 1105dwarf based call graphs: 11061. Need support of debug information in binaries. 11072. Behave normally well on both ARM and ARM64, for both fully compiled Java code and C++ code. 11083. 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. 11104. 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 1113stack frame based call graphs: 11141. Need support of stack frame registers. 11152. 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. 11173. Also don't work well on fully compiled Java code on ARM64. Because the ART compiler doesn't 1118 reserve stack frame registers. 11194. Work well when profiling native programs on ARM64. One example is profiling surfacelinger. And 1120 usually shows complete flame-graph when it works well. 11215. Take less CPU time than dwarf based call graphs. So the sample frequency can be 4000 Hz or 1122 higher. 1123 1124So if you need to profile code on ARM or profile fully compiled Java code, dwarf based call graphs 1125may be better. If you need to profile C++ code on ARM64, stack frame based call graphs may be 1126better. After all, you can always try dwarf based call graph first, because it always produces 1127reasonable results when given unstripped binaries properly. If it doesn't work well enough, then 1128try stack frame based call graphs instead. 1129 1130Simpleperf needs to have unstripped native binaries on the device to generate good dwarf based call 1131graphs. It can be supported in two ways: 11321. Use unstripped native binaries when building the apk, as [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleWithNative/app/profiling.gradle). 11332. 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 1142The simpleperf record command collects symbols on device in perf.data. But if the native libraries 1143you use on device are stripped, this will result in a lot of unknown symbols in the report. A 1144solution 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 1151The NATIVE_LIB_DIRs passed in -lib option are the directories containing unstripped native 1152libraries on host. After running it, the native libraries containing symbol tables are collected 1153in 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```