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.
28 #include <android-base/logging.h>
29 #include <android-base/strings.h>
32 #include "environment.h"
33 #include "event_attr.h"
35 #include "event_selection_set.h"
36 #include "event_type.h"
37 #include "scoped_signal_handler.h"
41 static std::vector<std::string> default_measured_event_types{
42 "cpu-cycles", "stalled-cycles-frontend", "stalled-cycles-backend",
43 "instructions", "branch-instructions", "branch-misses",
44 "task-clock", "context-switches", "page-faults",
47 static volatile bool signaled;
48 static void signal_handler(int) {
52 class StatCommand : public Command {
55 : Command("stat", "gather performance counter information",
56 "Usage: simpleperf stat [options] [command [command-args]]\n"
57 " Gather performance counter information of running [command].\n"
58 " -a Collect system-wide information.\n"
59 " --cpu cpu_item1,cpu_item2,...\n"
60 " Collect information only on the selected cpus. cpu_item can\n"
61 " be a cpu number like 1, or a cpu range like 0-3.\n"
62 " -e event1[:modifier1],event2[:modifier2],...\n"
63 " Select the event list to count. Use `simpleperf list` to find\n"
64 " all possible event names. Modifiers can be added to define\n"
65 " how the event should be monitored. Possible modifiers are:\n"
66 " u - monitor user space events only\n"
67 " k - monitor kernel space events only\n"
69 " Don't stat created child threads/processes.\n"
71 " Stat events on existing processes. Mutually exclusive with -a.\n"
73 " Stat events on existing threads. Mutually exclusive with -a.\n"
74 " --verbose Show result in verbose mode.\n"),
76 system_wide_collection_(false),
77 child_inherit_(true) {
79 scoped_signal_handler_.reset(
80 new ScopedSignalHandler({SIGCHLD, SIGINT, SIGTERM}, signal_handler));
83 bool Run(const std::vector<std::string>& args);
86 bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args);
87 bool AddMeasuredEventType(const std::string& event_type_name);
88 bool AddDefaultMeasuredEventTypes();
89 bool SetEventSelection();
90 bool ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec);
93 bool system_wide_collection_;
95 std::vector<pid_t> monitored_threads_;
96 std::vector<int> cpus_;
97 std::vector<EventTypeAndModifier> measured_event_types_;
98 EventSelectionSet event_selection_set_;
100 std::unique_ptr<ScopedSignalHandler> scoped_signal_handler_;
103 bool StatCommand::Run(const std::vector<std::string>& args) {
104 // 1. Parse options, and use default measured event types if not given.
105 std::vector<std::string> workload_args;
106 if (!ParseOptions(args, &workload_args)) {
109 if (measured_event_types_.empty()) {
110 if (!AddDefaultMeasuredEventTypes()) {
114 if (!SetEventSelection()) {
118 // 2. Create workload.
119 std::unique_ptr<Workload> workload;
120 if (!workload_args.empty()) {
121 workload = Workload::CreateWorkload(workload_args);
122 if (workload == nullptr) {
126 if (!system_wide_collection_ && monitored_threads_.empty()) {
127 if (workload != nullptr) {
128 monitored_threads_.push_back(workload->GetPid());
129 event_selection_set_.SetEnableOnExec(true);
131 LOG(ERROR) << "No threads to monitor. Try `simpleperf help stat` for help\n";
136 // 3. Open perf_event_files.
137 if (system_wide_collection_) {
138 if (!event_selection_set_.OpenEventFilesForCpus(cpus_)) {
142 if (!event_selection_set_.OpenEventFilesForThreadsOnCpus(monitored_threads_, cpus_)) {
147 // 4. Count events while workload running.
148 auto start_time = std::chrono::steady_clock::now();
149 if (workload != nullptr && !workload->Start()) {
155 auto end_time = std::chrono::steady_clock::now();
157 // 5. Read and print counters.
158 std::vector<CountersInfo> counters;
159 if (!event_selection_set_.ReadCounters(&counters)) {
162 double duration_in_sec =
163 std::chrono::duration_cast<std::chrono::duration<double>>(end_time - start_time).count();
164 if (!ShowCounters(counters, duration_in_sec)) {
170 bool StatCommand::ParseOptions(const std::vector<std::string>& args,
171 std::vector<std::string>* non_option_args) {
172 std::set<pid_t> tid_set;
174 for (i = 0; i < args.size() && args[i].size() > 0 && args[i][0] == '-'; ++i) {
175 if (args[i] == "-a") {
176 system_wide_collection_ = true;
177 } else if (args[i] == "--cpu") {
178 if (!NextArgumentOrError(args, &i)) {
181 cpus_ = GetCpusFromString(args[i]);
182 } else if (args[i] == "-e") {
183 if (!NextArgumentOrError(args, &i)) {
186 std::vector<std::string> event_types = android::base::Split(args[i], ",");
187 for (auto& event_type : event_types) {
188 if (!AddMeasuredEventType(event_type)) {
192 } else if (args[i] == "--no-inherit") {
193 child_inherit_ = false;
194 } else if (args[i] == "-p") {
195 if (!NextArgumentOrError(args, &i)) {
198 if (!GetValidThreadsFromProcessString(args[i], &tid_set)) {
201 } else if (args[i] == "-t") {
202 if (!NextArgumentOrError(args, &i)) {
205 if (!GetValidThreadsFromThreadString(args[i], &tid_set)) {
208 } else if (args[i] == "--verbose") {
209 verbose_mode_ = true;
211 ReportUnknownOption(args, i);
216 monitored_threads_.insert(monitored_threads_.end(), tid_set.begin(), tid_set.end());
217 if (system_wide_collection_ && !monitored_threads_.empty()) {
218 LOG(ERROR) << "Stat system wide and existing processes/threads can't be used at the same time.";
222 if (non_option_args != nullptr) {
223 non_option_args->clear();
224 for (; i < args.size(); ++i) {
225 non_option_args->push_back(args[i]);
231 bool StatCommand::AddMeasuredEventType(const std::string& event_type_name) {
232 std::unique_ptr<EventTypeAndModifier> event_type_modifier = ParseEventType(event_type_name);
233 if (event_type_modifier == nullptr) {
236 measured_event_types_.push_back(*event_type_modifier);
240 bool StatCommand::AddDefaultMeasuredEventTypes() {
241 for (auto& name : default_measured_event_types) {
242 // It is not an error when some event types in the default list are not supported by the kernel.
243 const EventType* type = FindEventTypeByName(name);
244 if (type != nullptr && IsEventAttrSupportedByKernel(CreateDefaultPerfEventAttr(*type))) {
245 AddMeasuredEventType(name);
248 if (measured_event_types_.empty()) {
249 LOG(ERROR) << "Failed to add any supported default measured types";
255 bool StatCommand::SetEventSelection() {
256 for (auto& event_type : measured_event_types_) {
257 if (!event_selection_set_.AddEventType(event_type)) {
261 event_selection_set_.SetInherit(child_inherit_);
265 static std::string ReadableCountValue(uint64_t count,
266 const EventTypeAndModifier& event_type_modifier) {
267 if (event_type_modifier.event_type.name == "cpu-clock" ||
268 event_type_modifier.event_type.name == "task-clock") {
269 double value = count / 1e6;
270 return android::base::StringPrintf("%lf(ms)", value);
272 std::string s = android::base::StringPrintf("%" PRIu64, count);
273 for (size_t i = s.size() - 1, j = 1; i > 0; --i, ++j) {
275 s.insert(s.begin() + i, ',');
283 struct CounterSummary {
284 const EventTypeAndModifier* event_type;
287 std::string readable_count_str;
291 static std::string GetCommentForSummary(const CounterSummary& summary,
292 const std::vector<CounterSummary>& summaries,
293 double duration_in_sec) {
294 const std::string& type_name = summary.event_type->event_type.name;
295 const std::string& modifier = summary.event_type->modifier;
296 if (type_name == "task-clock") {
297 double run_sec = summary.count / 1e9;
298 double cpu_usage = run_sec / duration_in_sec;
299 return android::base::StringPrintf("%lf%% cpu usage", cpu_usage * 100);
301 if (type_name == "cpu-clock") {
304 if (type_name == "cpu-cycles") {
305 double hz = summary.count / duration_in_sec;
306 return android::base::StringPrintf("%lf GHz", hz / 1e9);
308 if (type_name == "instructions" && summary.count != 0) {
309 for (auto& t : summaries) {
310 if (t.event_type->event_type.name == "cpu-cycles" && t.event_type->modifier == modifier) {
311 double cycles_per_instruction = t.count * 1.0 / summary.count;
312 return android::base::StringPrintf("%lf cycles per instruction", cycles_per_instruction);
316 if (android::base::EndsWith(type_name, "-misses")) {
318 if (type_name == "cache-misses") {
319 s = "cache-references";
320 } else if (type_name == "branch-misses") {
321 s = "branch-instructions";
323 s = type_name.substr(0, type_name.size() - strlen("-misses")) + "s";
325 for (auto& t : summaries) {
326 if (t.event_type->event_type.name == s && t.event_type->modifier == modifier && t.count != 0) {
327 double miss_rate = summary.count * 1.0 / t.count;
328 return android::base::StringPrintf("%lf%% miss rate", miss_rate * 100);
332 double rate = summary.count / duration_in_sec;
334 return android::base::StringPrintf("%.3lf G/sec", rate / 1e9);
337 return android::base::StringPrintf("%.3lf M/sec", rate / 1e6);
340 return android::base::StringPrintf("%.3lf K/sec", rate / 1e3);
342 return android::base::StringPrintf("%.3lf /sec", rate);
345 bool StatCommand::ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec) {
346 printf("Performance counter statistics:\n\n");
349 for (auto& counters_info : counters) {
350 const EventTypeAndModifier* event_type = counters_info.event_type;
351 for (auto& counter_info : counters_info.counters) {
352 printf("%s(tid %d, cpu %d): count %s, time_enabled %" PRIu64 ", time running %" PRIu64
353 ", id %" PRIu64 "\n",
354 event_type->name.c_str(), counter_info.tid, counter_info.cpu,
355 ReadableCountValue(counter_info.counter.value, *event_type).c_str(),
356 counter_info.counter.time_enabled, counter_info.counter.time_running,
357 counter_info.counter.id);
362 std::vector<CounterSummary> summaries;
363 for (auto& counters_info : counters) {
364 uint64_t value_sum = 0;
365 uint64_t time_enabled_sum = 0;
366 uint64_t time_running_sum = 0;
367 for (auto& counter_info : counters_info.counters) {
368 value_sum += counter_info.counter.value;
369 time_enabled_sum += counter_info.counter.time_enabled;
370 time_running_sum += counter_info.counter.time_running;
373 uint64_t scaled_count = value_sum;
374 if (time_running_sum < time_enabled_sum) {
375 if (time_running_sum == 0) {
378 scale = static_cast<double>(time_enabled_sum) / time_running_sum;
379 scaled_count = static_cast<uint64_t>(scale * value_sum);
382 CounterSummary summary;
383 summary.event_type = counters_info.event_type;
384 summary.count = scaled_count;
385 summary.scale = scale;
386 summary.readable_count_str = ReadableCountValue(summary.count, *summary.event_type);
387 summaries.push_back(summary);
390 for (auto& summary : summaries) {
391 summary.comment = GetCommentForSummary(summary, summaries, duration_in_sec);
394 size_t count_column_width = 0;
395 size_t name_column_width = 0;
396 size_t comment_column_width = 0;
397 for (auto& summary : summaries) {
398 count_column_width = std::max(count_column_width, summary.readable_count_str.size());
399 name_column_width = std::max(name_column_width, summary.event_type->name.size());
400 comment_column_width = std::max(comment_column_width, summary.comment.size());
403 for (auto& summary : summaries) {
404 printf(" %*s %-*s # %-*s (%.0lf%%)\n", static_cast<int>(count_column_width),
405 summary.readable_count_str.c_str(), static_cast<int>(name_column_width),
406 summary.event_type->name.c_str(), static_cast<int>(comment_column_width),
407 summary.comment.c_str(), 1.0 / summary.scale * 100);
410 printf("\nTotal test time: %lf seconds.\n", duration_in_sec);
414 void RegisterStatCommand() {
415 RegisterCommand("stat", [] { return std::unique_ptr<Command>(new StatCommand); });