OSDN Git Service

Merge "Simpleperf: fix the process of parsing records."
[android-x86/system-extras.git] / simpleperf / cmd_stat.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <inttypes.h>
18 #include <signal.h>
19 #include <stdio.h>
20 #include <chrono>
21 #include <set>
22 #include <string>
23 #include <vector>
24
25 #include <base/logging.h>
26 #include <base/strings.h>
27
28 #include "command.h"
29 #include "environment.h"
30 #include "event_attr.h"
31 #include "event_fd.h"
32 #include "event_selection_set.h"
33 #include "event_type.h"
34 #include "utils.h"
35 #include "workload.h"
36
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",
41 };
42
43 static volatile bool signaled;
44 static void signal_handler(int) {
45   signaled = true;
46 }
47
48 class StatCommand : public Command {
49  public:
50   StatCommand()
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"
61                 "    --no-inherit\n"
62                 "                 Don't stat created child threads/processes.\n"
63                 "    -p pid1,pid2,...\n"
64                 "                 Stat events on existing processes. Mutually exclusive with -a.\n"
65                 "    -t tid1,tid2,...\n"
66                 "                 Stat events on existing threads. Mutually exclusive with -a.\n"
67                 "    --verbose    Show result in verbose mode.\n"),
68         verbose_mode_(false),
69         system_wide_collection_(false),
70         child_inherit_(true) {
71     signaled = false;
72     signal_handler_register_.reset(
73         new SignalHandlerRegister({SIGCHLD, SIGINT, SIGTERM}, signal_handler));
74   }
75
76   bool Run(const std::vector<std::string>& args);
77
78  private:
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();
83   bool ShowCounters(
84       const std::map<const EventTypeAndModifier*, std::vector<PerfCounter>>& counters_map,
85       std::chrono::steady_clock::duration counting_duration);
86
87   bool verbose_mode_;
88   bool system_wide_collection_;
89   bool child_inherit_;
90   std::vector<pid_t> monitored_threads_;
91   std::vector<EventTypeAndModifier> measured_event_types_;
92   EventSelectionSet event_selection_set_;
93
94   std::unique_ptr<SignalHandlerRegister> signal_handler_register_;
95 };
96
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)) {
101     return false;
102   }
103   if (measured_event_types_.empty()) {
104     if (!AddDefaultMeasuredEventTypes()) {
105       return false;
106     }
107   }
108   if (!SetEventSelection()) {
109     return false;
110   }
111
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) {
117       return false;
118     }
119   }
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);
124     } else {
125       LOG(ERROR) << "No threads to monitor. Try `simpleperf help stat` for help\n";
126       return false;
127     }
128   }
129
130   // 3. Open perf_event_files.
131   if (system_wide_collection_) {
132     if (!event_selection_set_.OpenEventFilesForAllCpus()) {
133       return false;
134     }
135   } else {
136     if (!event_selection_set_.OpenEventFilesForThreads(monitored_threads_)) {
137       return false;
138     }
139   }
140
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()) {
145       return false;
146     }
147   }
148   if (workload != nullptr && !workload->Start()) {
149     return false;
150   }
151   while (!signaled) {
152     sleep(1);
153   }
154   auto end_time = std::chrono::steady_clock::now();
155
156   // 5. Read and print counters.
157   std::map<const EventTypeAndModifier*, std::vector<PerfCounter>> counters_map;
158   if (!event_selection_set_.ReadCounters(&counters_map)) {
159     return false;
160   }
161   if (!ShowCounters(counters_map, end_time - start_time)) {
162     return false;
163   }
164   return true;
165 }
166
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;
170   size_t i;
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)) {
176         return false;
177       }
178       std::vector<std::string> event_types = android::base::Split(args[i], ",");
179       for (auto& event_type : event_types) {
180         if (!AddMeasuredEventType(event_type)) {
181           return false;
182         }
183       }
184     } else if (args[i] == "--no-inherit") {
185       child_inherit_ = false;
186     } else if (args[i] == "-p") {
187       if (!NextArgumentOrError(args, &i)) {
188         return false;
189       }
190       if (!GetValidThreadsFromProcessString(args[i], &tid_set)) {
191         return false;
192       }
193     } else if (args[i] == "-t") {
194       if (!NextArgumentOrError(args, &i)) {
195         return false;
196       }
197       if (!GetValidThreadsFromThreadString(args[i], &tid_set)) {
198         return false;
199       }
200     } else if (args[i] == "--verbose") {
201       verbose_mode_ = true;
202     } else {
203       ReportUnknownOption(args, i);
204       return false;
205     }
206   }
207
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.";
211     return false;
212   }
213
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]);
218     }
219   }
220   return true;
221 }
222
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) {
226     return false;
227   }
228   measured_event_types_.push_back(*event_type_modifier);
229   return true;
230 }
231
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);
238     }
239   }
240   if (measured_event_types_.empty()) {
241     LOG(ERROR) << "Failed to add any supported default measured types";
242     return false;
243   }
244   return true;
245 }
246
247 bool StatCommand::SetEventSelection() {
248   for (auto& event_type : measured_event_types_) {
249     if (!event_selection_set_.AddEventType(event_type)) {
250       return false;
251     }
252   }
253   event_selection_set_.SetInherit(child_inherit_);
254   return true;
255 }
256
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");
261
262   for (auto& pair : counters_map) {
263     auto& event_type_modifier = pair.first;
264     auto& counters = pair.second;
265     if (verbose_mode_) {
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);
271       }
272     }
273
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;
280     }
281     bool scaled = false;
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) {
285         scaled_count = 0;
286       } else {
287         scaled = true;
288         scaled_count = static_cast<int64_t>(static_cast<double>(sum_counter.value) *
289                                             sum_counter.time_enabled / sum_counter.time_running);
290       }
291     }
292     printf("%'30" PRId64 "%s  %s\n", scaled_count, scaled ? "(scaled)" : "       ",
293            event_type_modifier->name.c_str());
294   }
295   printf("\nTotal test time: %lf seconds.\n",
296          std::chrono::duration_cast<std::chrono::duration<double>>(counting_duration).count());
297   return true;
298 }
299
300 __attribute__((constructor)) static void RegisterStatCommand() {
301   RegisterCommand("stat", [] { return std::unique_ptr<Command>(new StatCommand); });
302 }