2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
25 #include <base/logging.h>
26 #include <base/strings.h>
29 #include "environment.h"
30 #include "event_attr.h"
32 #include "event_selection_set.h"
33 #include "event_type.h"
37 static std::vector<std::string> default_measured_event_types{
38 "cpu-cycles", "stalled-cycles-frontend", "stalled-cycles-backend",
39 "instructions", "branch-instructions", "branch-misses",
40 "task-clock", "context-switches", "page-faults",
43 static volatile bool signaled;
44 static void signal_handler(int) {
48 class StatCommand : public Command {
51 : Command("stat", "gather performance counter information",
52 "Usage: simpleperf stat [options] [command [command-args]]\n"
53 " Gather performance counter information of running [command].\n"
54 " -a Collect system-wide information.\n"
55 " -e event1[:modifier1],event2[:modifier2],...\n"
56 " Select the event list to count. Use `simpleperf list` to find\n"
57 " all possible event names. Modifiers can be added to define\n"
58 " how the event should be monitored. Possible modifiers are:\n"
59 " u - monitor user space events only\n"
60 " k - monitor kernel space events only\n"
62 " Don't stat created child threads/processes.\n"
64 " Stat events on existing processes. Mutually exclusive with -a.\n"
66 " Stat events on existing threads. Mutually exclusive with -a.\n"
67 " --verbose Show result in verbose mode.\n"),
69 system_wide_collection_(false),
70 child_inherit_(true) {
72 signal_handler_register_.reset(
73 new SignalHandlerRegister({SIGCHLD, SIGINT, SIGTERM}, signal_handler));
76 bool Run(const std::vector<std::string>& args);
79 bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args);
80 bool AddMeasuredEventType(const std::string& event_type_name);
81 bool AddDefaultMeasuredEventTypes();
82 bool SetEventSelection();
84 const std::map<const EventTypeAndModifier*, std::vector<PerfCounter>>& counters_map,
85 std::chrono::steady_clock::duration counting_duration);
88 bool system_wide_collection_;
90 std::vector<pid_t> monitored_threads_;
91 std::vector<EventTypeAndModifier> measured_event_types_;
92 EventSelectionSet event_selection_set_;
94 std::unique_ptr<SignalHandlerRegister> signal_handler_register_;
97 bool StatCommand::Run(const std::vector<std::string>& args) {
98 // 1. Parse options, and use default measured event types if not given.
99 std::vector<std::string> workload_args;
100 if (!ParseOptions(args, &workload_args)) {
103 if (measured_event_types_.empty()) {
104 if (!AddDefaultMeasuredEventTypes()) {
108 if (!SetEventSelection()) {
112 // 2. Create workload.
113 std::unique_ptr<Workload> workload;
114 if (!workload_args.empty()) {
115 workload = Workload::CreateWorkload(workload_args);
116 if (workload == nullptr) {
120 if (!system_wide_collection_ && monitored_threads_.empty()) {
121 if (workload != nullptr) {
122 monitored_threads_.push_back(workload->GetPid());
123 event_selection_set_.SetEnableOnExec(true);
125 LOG(ERROR) << "No threads to monitor. Try `simpleperf help stat` for help\n";
130 // 3. Open perf_event_files.
131 if (system_wide_collection_) {
132 if (!event_selection_set_.OpenEventFilesForAllCpus()) {
136 if (!event_selection_set_.OpenEventFilesForThreads(monitored_threads_)) {
141 // 4. Count events while workload running.
142 auto start_time = std::chrono::steady_clock::now();
143 if (!event_selection_set_.GetEnableOnExec()) {
144 if (!event_selection_set_.EnableEvents()) {
148 if (workload != nullptr && !workload->Start()) {
154 auto end_time = std::chrono::steady_clock::now();
156 // 5. Read and print counters.
157 std::map<const EventTypeAndModifier*, std::vector<PerfCounter>> counters_map;
158 if (!event_selection_set_.ReadCounters(&counters_map)) {
161 if (!ShowCounters(counters_map, end_time - start_time)) {
167 bool StatCommand::ParseOptions(const std::vector<std::string>& args,
168 std::vector<std::string>* non_option_args) {
169 std::set<pid_t> tid_set;
171 for (i = 0; i < args.size() && args[i].size() > 0 && args[i][0] == '-'; ++i) {
172 if (args[i] == "-a") {
173 system_wide_collection_ = true;
174 } else if (args[i] == "-e") {
175 if (!NextArgumentOrError(args, &i)) {
178 std::vector<std::string> event_types = android::base::Split(args[i], ",");
179 for (auto& event_type : event_types) {
180 if (!AddMeasuredEventType(event_type)) {
184 } else if (args[i] == "--no-inherit") {
185 child_inherit_ = false;
186 } else if (args[i] == "-p") {
187 if (!NextArgumentOrError(args, &i)) {
190 if (!GetValidThreadsFromProcessString(args[i], &tid_set)) {
193 } else if (args[i] == "-t") {
194 if (!NextArgumentOrError(args, &i)) {
197 if (!GetValidThreadsFromThreadString(args[i], &tid_set)) {
200 } else if (args[i] == "--verbose") {
201 verbose_mode_ = true;
203 ReportUnknownOption(args, i);
208 monitored_threads_.insert(monitored_threads_.end(), tid_set.begin(), tid_set.end());
209 if (system_wide_collection_ && !monitored_threads_.empty()) {
210 LOG(ERROR) << "Stat system wide and existing processes/threads can't be used at the same time.";
214 if (non_option_args != nullptr) {
215 non_option_args->clear();
216 for (; i < args.size(); ++i) {
217 non_option_args->push_back(args[i]);
223 bool StatCommand::AddMeasuredEventType(const std::string& event_type_name) {
224 std::unique_ptr<EventTypeAndModifier> event_type_modifier = ParseEventType(event_type_name);
225 if (event_type_modifier == nullptr) {
228 measured_event_types_.push_back(*event_type_modifier);
232 bool StatCommand::AddDefaultMeasuredEventTypes() {
233 for (auto& name : default_measured_event_types) {
234 // It is not an error when some event types in the default list are not supported by the kernel.
235 const EventType* type = FindEventTypeByName(name);
236 if (type != nullptr && IsEventAttrSupportedByKernel(CreateDefaultPerfEventAttr(*type))) {
237 AddMeasuredEventType(name);
240 if (measured_event_types_.empty()) {
241 LOG(ERROR) << "Failed to add any supported default measured types";
247 bool StatCommand::SetEventSelection() {
248 for (auto& event_type : measured_event_types_) {
249 if (!event_selection_set_.AddEventType(event_type)) {
253 event_selection_set_.SetInherit(child_inherit_);
257 bool StatCommand::ShowCounters(
258 const std::map<const EventTypeAndModifier*, std::vector<PerfCounter>>& counters_map,
259 std::chrono::steady_clock::duration counting_duration) {
260 printf("Performance counter statistics:\n\n");
262 for (auto& pair : counters_map) {
263 auto& event_type_modifier = pair.first;
264 auto& counters = pair.second;
266 for (auto& counter : counters) {
267 printf("%s: value %'" PRId64 ", time_enabled %" PRId64 ", time_running %" PRId64
268 ", id %" PRId64 "\n",
269 event_selection_set_.FindEventFileNameById(counter.id).c_str(), counter.value,
270 counter.time_enabled, counter.time_running, counter.id);
274 PerfCounter sum_counter;
275 memset(&sum_counter, 0, sizeof(sum_counter));
276 for (auto& counter : counters) {
277 sum_counter.value += counter.value;
278 sum_counter.time_enabled += counter.time_enabled;
279 sum_counter.time_running += counter.time_running;
282 int64_t scaled_count = sum_counter.value;
283 if (sum_counter.time_running < sum_counter.time_enabled) {
284 if (sum_counter.time_running == 0) {
288 scaled_count = static_cast<int64_t>(static_cast<double>(sum_counter.value) *
289 sum_counter.time_enabled / sum_counter.time_running);
292 printf("%'30" PRId64 "%s %s\n", scaled_count, scaled ? "(scaled)" : " ",
293 event_type_modifier->name.c_str());
295 printf("\nTotal test time: %lf seconds.\n",
296 std::chrono::duration_cast<std::chrono::duration<double>>(counting_duration).count());
300 __attribute__((constructor)) static void RegisterStatCommand() {
301 RegisterCommand("stat", [] { return std::unique_ptr<Command>(new StatCommand); });