blob: a0929bcf169e2bc5b5da954dc64a046267d27d32 [file] [log] [blame]
Yabin Cui323e9452015-04-20 18:07:17 -07001/*
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>
Yabin Cui621a5332015-06-15 16:17:20 -070018#include <signal.h>
Yabin Cui323e9452015-04-20 18:07:17 -070019#include <stdio.h>
Yabin Cui04d08a32015-08-19 15:01:12 -070020#include <string.h>
Yabin Cui987d9ab2016-07-15 14:08:48 -070021#include <sys/prctl.h>
Yabin Cui04d08a32015-08-19 15:01:12 -070022
23#include <algorithm>
Yabin Cui323e9452015-04-20 18:07:17 -070024#include <chrono>
Yabin Cuib032de72015-06-17 21:15:09 -070025#include <set>
Yabin Cui323e9452015-04-20 18:07:17 -070026#include <string>
27#include <vector>
28
Elliott Hughes66dd09e2015-12-04 14:00:57 -080029#include <android-base/logging.h>
Yabin Cuic0565bb2016-09-29 15:59:33 -070030#include <android-base/parsedouble.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080031#include <android-base/strings.h>
Yabin Cui323e9452015-04-20 18:07:17 -070032
33#include "command.h"
34#include "environment.h"
Yabin Cui9fd3cc12015-06-25 17:42:23 -070035#include "event_attr.h"
36#include "event_fd.h"
Yabin Cui9759e1b2015-04-28 15:54:13 -070037#include "event_selection_set.h"
Yabin Cui323e9452015-04-20 18:07:17 -070038#include "event_type.h"
Yabin Cui3e4c5952016-07-26 15:03:27 -070039#include "IOEventLoop.h"
Yabin Cui621a5332015-06-15 16:17:20 -070040#include "utils.h"
Yabin Cui323e9452015-04-20 18:07:17 -070041#include "workload.h"
42
Yabin Cui877751b2016-06-13 18:03:47 -070043namespace {
44
Yabin Cui323e9452015-04-20 18:07:17 -070045static std::vector<std::string> default_measured_event_types{
Yabin Cuif569b472015-04-30 09:43:26 -070046 "cpu-cycles", "stalled-cycles-frontend", "stalled-cycles-backend",
47 "instructions", "branch-instructions", "branch-misses",
48 "task-clock", "context-switches", "page-faults",
Yabin Cui323e9452015-04-20 18:07:17 -070049};
50
Yabin Cui0a45adf2016-06-22 20:58:52 -070051struct CounterSummary {
52 std::string type_name;
53 std::string modifier;
54 uint32_t group_id;
55 uint64_t count;
56 double scale;
57 std::string readable_count;
58 std::string comment;
59 bool auto_generated;
60
61 CounterSummary(const std::string& type_name, const std::string& modifier,
62 uint32_t group_id, uint64_t count, double scale,
Zhiting Zhu0979ba82016-07-09 19:38:08 -070063 bool auto_generated, bool csv)
Yabin Cui0a45adf2016-06-22 20:58:52 -070064 : type_name(type_name),
65 modifier(modifier),
66 group_id(group_id),
67 count(count),
68 scale(scale),
69 auto_generated(auto_generated) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -070070 readable_count = ReadableCountValue(csv);
Yabin Cui0a45adf2016-06-22 20:58:52 -070071 }
72
73 bool IsMonitoredAtTheSameTime(const CounterSummary& other) const {
74 // Two summaries are monitored at the same time if they are in the same
75 // group or are monitored all the time.
76 if (group_id == other.group_id) {
77 return true;
78 }
79 return IsMonitoredAllTheTime() && other.IsMonitoredAllTheTime();
80 }
81
82 std::string Name() const {
83 if (modifier.empty()) {
84 return type_name;
85 }
86 return type_name + ":" + modifier;
87 }
88
89 private:
Zhiting Zhu0979ba82016-07-09 19:38:08 -070090 std::string ReadableCountValue(bool csv) {
Yabin Cui0a45adf2016-06-22 20:58:52 -070091 if (type_name == "cpu-clock" || type_name == "task-clock") {
92 // Convert nanoseconds to milliseconds.
93 double value = count / 1e6;
94 return android::base::StringPrintf("%lf(ms)", value);
95 } else {
96 // Convert big numbers to human friendly mode. For example,
97 // 1000000 will be converted to 1,000,000.
98 std::string s = android::base::StringPrintf("%" PRIu64, count);
Zhiting Zhu0979ba82016-07-09 19:38:08 -070099 if (csv) {
100 return s;
101 } else {
102 for (size_t i = s.size() - 1, j = 1; i > 0; --i, ++j) {
103 if (j == 3) {
104 s.insert(s.begin() + i, ',');
105 j = 0;
106 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700107 }
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700108 return s;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700109 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700110 }
111 }
112
113 bool IsMonitoredAllTheTime() const {
114 // If an event runs all the time it is enabled (by not sharing hardware
115 // counters with other events), the scale of its summary is usually within
116 // [1, 1 + 1e-5]. By setting SCALE_ERROR_LIMIT to 1e-5, We can identify
117 // events monitored all the time in most cases while keeping the report
118 // error rate <= 1e-5.
119 constexpr double SCALE_ERROR_LIMIT = 1e-5;
120 return (fabs(scale - 1.0) < SCALE_ERROR_LIMIT);
121 }
122};
123
124class CounterSummaries {
125 public:
Yabin Cui8a599d72016-07-21 18:32:53 -0700126 explicit CounterSummaries(bool csv) : csv_(csv) {}
Yabin Cui0a45adf2016-06-22 20:58:52 -0700127 void AddSummary(const CounterSummary& summary) {
128 summaries_.push_back(summary);
129 }
130
131 const CounterSummary* FindSummary(const std::string& type_name,
132 const std::string& modifier) {
133 for (const auto& s : summaries_) {
134 if (s.type_name == type_name && s.modifier == modifier) {
135 return &s;
136 }
137 }
138 return nullptr;
139 }
140
141 // If we have two summaries monitoring the same event type at the same time,
142 // that one is for user space only, and the other is for kernel space only;
143 // then we can automatically generate a summary combining the two results.
144 // For example, a summary of branch-misses:u and a summary for branch-misses:k
145 // can generate a summary of branch-misses.
146 void AutoGenerateSummaries() {
147 for (size_t i = 0; i < summaries_.size(); ++i) {
148 const CounterSummary& s = summaries_[i];
149 if (s.modifier == "u") {
150 const CounterSummary* other = FindSummary(s.type_name, "k");
151 if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
152 if (FindSummary(s.type_name, "") == nullptr) {
153 AddSummary(CounterSummary(s.type_name, "", s.group_id,
Yabin Cui8a599d72016-07-21 18:32:53 -0700154 s.count + other->count, s.scale, true,
155 csv_));
Yabin Cui0a45adf2016-06-22 20:58:52 -0700156 }
157 }
158 }
159 }
160 }
161
162 void GenerateComments(double duration_in_sec) {
163 for (auto& s : summaries_) {
164 s.comment = GetCommentForSummary(s, duration_in_sec);
165 }
166 }
167
168 void Show(FILE* fp) {
169 size_t count_column_width = 0;
170 size_t name_column_width = 0;
171 size_t comment_column_width = 0;
172 for (auto& s : summaries_) {
173 count_column_width =
174 std::max(count_column_width, s.readable_count.size());
175 name_column_width = std::max(name_column_width, s.Name().size());
176 comment_column_width = std::max(comment_column_width, s.comment.size());
177 }
178
179 for (auto& s : summaries_) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700180 if (csv_) {
Yabin Cui8a599d72016-07-21 18:32:53 -0700181 fprintf(fp, "%s,%s,%s,(%.0lf%%)%s\n", s.readable_count.c_str(),
182 s.Name().c_str(), s.comment.c_str(), 1.0 / s.scale * 100,
183 (s.auto_generated ? " (generated)," : ","));
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700184 } else {
185 fprintf(fp, " %*s %-*s # %-*s (%.0lf%%)%s\n",
186 static_cast<int>(count_column_width), s.readable_count.c_str(),
187 static_cast<int>(name_column_width), s.Name().c_str(),
188 static_cast<int>(comment_column_width), s.comment.c_str(),
189 1.0 / s.scale * 100, (s.auto_generated ? " (generated)" : ""));
190 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700191 }
192 }
193
194 private:
195 std::string GetCommentForSummary(const CounterSummary& s,
196 double duration_in_sec) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700197 char sap_mid;
198 if (csv_) {
199 sap_mid = ',';
200 } else {
201 sap_mid = ' ';
202 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700203 if (s.type_name == "task-clock") {
204 double run_sec = s.count / 1e9;
205 double used_cpus = run_sec / (duration_in_sec / s.scale);
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700206 return android::base::StringPrintf("%lf%ccpus used", used_cpus, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700207 }
208 if (s.type_name == "cpu-clock") {
209 return "";
210 }
211 if (s.type_name == "cpu-cycles") {
212 double hz = s.count / (duration_in_sec / s.scale);
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700213 return android::base::StringPrintf("%lf%cGHz", hz / 1e9, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700214 }
215 if (s.type_name == "instructions" && s.count != 0) {
216 const CounterSummary* other = FindSummary("cpu-cycles", s.modifier);
217 if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
218 double cpi = static_cast<double>(other->count) / s.count;
Yabin Cui8a599d72016-07-21 18:32:53 -0700219 return android::base::StringPrintf("%lf%ccycles per instruction", cpi,
220 sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700221 }
222 }
223 if (android::base::EndsWith(s.type_name, "-misses")) {
224 std::string other_name;
225 if (s.type_name == "cache-misses") {
226 other_name = "cache-references";
227 } else if (s.type_name == "branch-misses") {
228 other_name = "branch-instructions";
229 } else {
230 other_name =
231 s.type_name.substr(0, s.type_name.size() - strlen("-misses")) + "s";
232 }
233 const CounterSummary* other = FindSummary(other_name, s.modifier);
234 if (other != nullptr && other->IsMonitoredAtTheSameTime(s) &&
235 other->count != 0) {
236 double miss_rate = static_cast<double>(s.count) / other->count;
Yabin Cui8a599d72016-07-21 18:32:53 -0700237 return android::base::StringPrintf("%lf%%%cmiss rate", miss_rate * 100,
238 sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700239 }
240 }
Yabin Cui43301382017-05-09 17:31:05 -0700241 if (android::base::EndsWith(s.type_name, "-refill")) {
242 std::string other_name = s.type_name.substr(0, s.type_name.size() - strlen("-refill"));
243 const CounterSummary* other = FindSummary(other_name, s.modifier);
244 if (other != nullptr && other->IsMonitoredAtTheSameTime(s) && other->count != 0) {
245 double miss_rate = static_cast<double>(s.count) / other->count;
246 return android::base::StringPrintf("%f%%%cmiss rate", miss_rate * 100, sap_mid);
247 }
248 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700249 double rate = s.count / (duration_in_sec / s.scale);
250 if (rate > 1e9) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700251 return android::base::StringPrintf("%.3lf%cG/sec", rate / 1e9, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700252 }
253 if (rate > 1e6) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700254 return android::base::StringPrintf("%.3lf%cM/sec", rate / 1e6, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700255 }
256 if (rate > 1e3) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700257 return android::base::StringPrintf("%.3lf%cK/sec", rate / 1e3, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700258 }
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700259 return android::base::StringPrintf("%.3lf%c/sec", rate, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700260 }
261
262 private:
263 std::vector<CounterSummary> summaries_;
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700264 bool csv_;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700265};
266
Yabin Cuif79f07e2015-06-01 11:21:37 -0700267class StatCommand : public Command {
Yabin Cui323e9452015-04-20 18:07:17 -0700268 public:
Yabin Cuif79f07e2015-06-01 11:21:37 -0700269 StatCommand()
Yabin Cui8a599d72016-07-21 18:32:53 -0700270 : Command("stat", "gather performance counter information",
271 // clang-format off
Yabin Cui877751b2016-06-13 18:03:47 -0700272"Usage: simpleperf stat [options] [command [command-args]]\n"
Yabin Cui8a599d72016-07-21 18:32:53 -0700273" Gather performance counter information of running [command].\n"
274" And -a/-p/-t option can be used to change target of counter information.\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700275"-a Collect system-wide information.\n"
276"--cpu cpu_item1,cpu_item2,...\n"
277" Collect information only on the selected cpus. cpu_item can\n"
278" be a cpu number like 1, or a cpu range like 0-3.\n"
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700279"--csv Write report in comma separate form.\n"
Yabin Cui8a599d72016-07-21 18:32:53 -0700280"--duration time_in_sec Monitor for time_in_sec seconds instead of running\n"
281" [command]. Here time_in_sec may be any positive\n"
282" floating point number.\n"
Wei Wang539fb882016-09-28 14:42:02 -0700283"--interval time_in_ms Print stat for every time_in_ms milliseconds.\n"
284" Here time_in_ms may be any positive floating point\n"
285" number.\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700286"-e event1[:modifier1],event2[:modifier2],...\n"
287" Select the event list to count. Use `simpleperf list` to find\n"
288" all possible event names. Modifiers can be added to define\n"
289" how the event should be monitored. Possible modifiers are:\n"
290" u - monitor user space events only\n"
291" k - monitor kernel space events only\n"
292"--group event1[:modifier],event2[:modifier2],...\n"
293" Similar to -e option. But events specified in the same --group\n"
294" option are monitored as a group, and scheduled in and out at the\n"
295" same time.\n"
296"--no-inherit Don't stat created child threads/processes.\n"
Yabin Cui0a45adf2016-06-22 20:58:52 -0700297"-o output_filename Write report to output_filename instead of standard output.\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700298"-p pid1,pid2,... Stat events on existing processes. Mutually exclusive with -a.\n"
299"-t tid1,tid2,... Stat events on existing threads. Mutually exclusive with -a.\n"
300"--verbose Show result in verbose mode.\n"
Yabin Cui8a599d72016-07-21 18:32:53 -0700301 // clang-format on
302 ),
Yabin Cuif79f07e2015-06-01 11:21:37 -0700303 verbose_mode_(false),
Yabin Cui4be41262015-06-22 14:23:01 -0700304 system_wide_collection_(false),
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700305 child_inherit_(true),
Yabin Cui3e4c5952016-07-26 15:03:27 -0700306 duration_in_sec_(0),
Wei Wang539fb882016-09-28 14:42:02 -0700307 interval_in_ms_(0),
Yabin Cui4cf37d12016-08-19 15:42:39 -0700308 event_selection_set_(true),
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700309 csv_(false) {
Yabin Cui987d9ab2016-07-15 14:08:48 -0700310 // Die if parent exits.
311 prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
Yabin Cui323e9452015-04-20 18:07:17 -0700312 }
313
314 bool Run(const std::vector<std::string>& args);
315
316 private:
Yabin Cui877751b2016-06-13 18:03:47 -0700317 bool ParseOptions(const std::vector<std::string>& args,
318 std::vector<std::string>* non_option_args);
Yabin Cui323e9452015-04-20 18:07:17 -0700319 bool AddDefaultMeasuredEventTypes();
Yabin Cui877751b2016-06-13 18:03:47 -0700320 void SetEventSelectionFlags();
321 bool ShowCounters(const std::vector<CountersInfo>& counters,
Wei Wang539fb882016-09-28 14:42:02 -0700322 double duration_in_sec, FILE* fp);
Yabin Cui323e9452015-04-20 18:07:17 -0700323
Yabin Cui323e9452015-04-20 18:07:17 -0700324 bool verbose_mode_;
325 bool system_wide_collection_;
Yabin Cui4be41262015-06-22 14:23:01 -0700326 bool child_inherit_;
Yabin Cui3e4c5952016-07-26 15:03:27 -0700327 double duration_in_sec_;
Wei Wang539fb882016-09-28 14:42:02 -0700328 double interval_in_ms_;
Yabin Cuicb4c17e2015-10-26 16:15:29 -0700329 std::vector<int> cpus_;
Yabin Cui4be41262015-06-22 14:23:01 -0700330 EventSelectionSet event_selection_set_;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700331 std::string output_filename_;
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700332 bool csv_;
Yabin Cui323e9452015-04-20 18:07:17 -0700333};
334
Yabin Cuif79f07e2015-06-01 11:21:37 -0700335bool StatCommand::Run(const std::vector<std::string>& args) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700336 if (!CheckPerfEventLimit()) {
337 return false;
338 }
339
Yabin Cui4be41262015-06-22 14:23:01 -0700340 // 1. Parse options, and use default measured event types if not given.
Yabin Cui323e9452015-04-20 18:07:17 -0700341 std::vector<std::string> workload_args;
342 if (!ParseOptions(args, &workload_args)) {
343 return false;
344 }
Yabin Cui877751b2016-06-13 18:03:47 -0700345 if (event_selection_set_.empty()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700346 if (!AddDefaultMeasuredEventTypes()) {
347 return false;
348 }
349 }
Yabin Cui877751b2016-06-13 18:03:47 -0700350 SetEventSelectionFlags();
Yabin Cui323e9452015-04-20 18:07:17 -0700351
Yabin Cui4be41262015-06-22 14:23:01 -0700352 // 2. Create workload.
Yabin Cuib032de72015-06-17 21:15:09 -0700353 std::unique_ptr<Workload> workload;
354 if (!workload_args.empty()) {
355 workload = Workload::CreateWorkload(workload_args);
356 if (workload == nullptr) {
357 return false;
358 }
Yabin Cui323e9452015-04-20 18:07:17 -0700359 }
Yabin Cui5f43fc42016-12-13 13:47:49 -0800360 bool need_to_check_targets = false;
Yabin Cuibc2a1022016-08-29 12:33:17 -0700361 if (system_wide_collection_) {
362 event_selection_set_.AddMonitoredThreads({-1});
363 } else if (!event_selection_set_.HasMonitoredTarget()) {
Yabin Cuib032de72015-06-17 21:15:09 -0700364 if (workload != nullptr) {
Yabin Cuibc2a1022016-08-29 12:33:17 -0700365 event_selection_set_.AddMonitoredProcesses({workload->GetPid()});
Yabin Cuib032de72015-06-17 21:15:09 -0700366 event_selection_set_.SetEnableOnExec(true);
367 } else {
Yabin Cui877751b2016-06-13 18:03:47 -0700368 LOG(ERROR)
369 << "No threads to monitor. Try `simpleperf help stat` for help\n";
Yabin Cuib032de72015-06-17 21:15:09 -0700370 return false;
371 }
Yabin Cui5f43fc42016-12-13 13:47:49 -0800372 } else {
373 need_to_check_targets = true;
Yabin Cui323e9452015-04-20 18:07:17 -0700374 }
375
Wei Wang539fb882016-09-28 14:42:02 -0700376 // 3. Open perf_event_files and output file if defined.
Yabin Cuibc2a1022016-08-29 12:33:17 -0700377 if (!system_wide_collection_ && cpus_.empty()) {
378 cpus_.push_back(-1); // Monitor on all cpus.
379 }
380 if (!event_selection_set_.OpenEventFiles(cpus_)) {
381 return false;
Yabin Cui323e9452015-04-20 18:07:17 -0700382 }
Wei Wang539fb882016-09-28 14:42:02 -0700383 std::unique_ptr<FILE, decltype(&fclose)> fp_holder(nullptr, fclose);
384 FILE* fp = stdout;
385 if (!output_filename_.empty()) {
386 fp_holder.reset(fopen(output_filename_.c_str(), "w"));
387 if (fp_holder == nullptr) {
388 PLOG(ERROR) << "failed to open " << output_filename_;
389 return false;
390 }
391 fp = fp_holder.get();
392 }
Yabin Cui323e9452015-04-20 18:07:17 -0700393
Yabin Cui26968e62017-01-30 11:34:24 -0800394 // 4. Add signal/periodic Events.
Wei Wang539fb882016-09-28 14:42:02 -0700395 std::chrono::time_point<std::chrono::steady_clock> start_time;
396 std::vector<CountersInfo> counters;
Yabin Cuibc2a1022016-08-29 12:33:17 -0700397 if (system_wide_collection_ || (!cpus_.empty() && cpus_[0] != -1)) {
Yabin Cui5f43fc42016-12-13 13:47:49 -0800398 if (!event_selection_set_.HandleCpuHotplugEvents(cpus_)) {
Yabin Cui994cb622016-08-19 17:24:37 -0700399 return false;
400 }
401 }
Yabin Cui5f43fc42016-12-13 13:47:49 -0800402 if (need_to_check_targets && !event_selection_set_.StopWhenNoMoreTargets()) {
403 return false;
404 }
Yabin Cui26968e62017-01-30 11:34:24 -0800405 IOEventLoop* loop = event_selection_set_.GetIOEventLoop();
406 if (!loop->AddSignalEvents({SIGCHLD, SIGINT, SIGTERM, SIGHUP},
407 [&]() { return loop->ExitLoop(); })) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700408 return false;
409 }
410 if (duration_in_sec_ != 0) {
Yabin Cui26968e62017-01-30 11:34:24 -0800411 if (!loop->AddPeriodicEvent(SecondToTimeval(duration_in_sec_),
412 [&]() { return loop->ExitLoop(); })) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700413 return false;
414 }
415 }
Wei Wang539fb882016-09-28 14:42:02 -0700416 auto print_counters = [&]() {
417 auto end_time = std::chrono::steady_clock::now();
418 if (!event_selection_set_.ReadCounters(&counters)) {
419 return false;
420 }
421 double duration_in_sec =
422 std::chrono::duration_cast<std::chrono::duration<double>>(end_time -
423 start_time)
424 .count();
425 if (!ShowCounters(counters, duration_in_sec, fp)) {
426 return false;
427 }
428 return true;
429 };
430
431 if (interval_in_ms_ != 0) {
Yabin Cui26968e62017-01-30 11:34:24 -0800432 if (!loop->AddPeriodicEvent(SecondToTimeval(interval_in_ms_ / 1000.0),
433 print_counters)) {
Wei Wang539fb882016-09-28 14:42:02 -0700434 return false;
435 }
436 }
Yabin Cui3e4c5952016-07-26 15:03:27 -0700437
438 // 5. Count events while workload running.
Wei Wang539fb882016-09-28 14:42:02 -0700439 start_time = std::chrono::steady_clock::now();
Yabin Cuib032de72015-06-17 21:15:09 -0700440 if (workload != nullptr && !workload->Start()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700441 return false;
442 }
Yabin Cui26968e62017-01-30 11:34:24 -0800443 if (!loop->RunLoop()) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700444 return false;
Yabin Cui621a5332015-06-15 16:17:20 -0700445 }
Yabin Cui323e9452015-04-20 18:07:17 -0700446
Yabin Cui3e4c5952016-07-26 15:03:27 -0700447 // 6. Read and print counters.
Wei Wang539fb882016-09-28 14:42:02 -0700448
449 return print_counters();
Yabin Cui323e9452015-04-20 18:07:17 -0700450}
451
Yabin Cuif79f07e2015-06-01 11:21:37 -0700452bool StatCommand::ParseOptions(const std::vector<std::string>& args,
453 std::vector<std::string>* non_option_args) {
Yabin Cuib032de72015-06-17 21:15:09 -0700454 std::set<pid_t> tid_set;
Yabin Cui323e9452015-04-20 18:07:17 -0700455 size_t i;
Yabin Cuif79f07e2015-06-01 11:21:37 -0700456 for (i = 0; i < args.size() && args[i].size() > 0 && args[i][0] == '-'; ++i) {
Yabin Cui323e9452015-04-20 18:07:17 -0700457 if (args[i] == "-a") {
458 system_wide_collection_ = true;
Yabin Cuicb4c17e2015-10-26 16:15:29 -0700459 } else if (args[i] == "--cpu") {
460 if (!NextArgumentOrError(args, &i)) {
461 return false;
462 }
463 cpus_ = GetCpusFromString(args[i]);
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700464 } else if (args[i] == "--csv") {
465 csv_ = true;
Yabin Cui8a599d72016-07-21 18:32:53 -0700466 } else if (args[i] == "--duration") {
467 if (!NextArgumentOrError(args, &i)) {
468 return false;
469 }
Yabin Cuic0565bb2016-09-29 15:59:33 -0700470 if (!android::base::ParseDouble(args[i].c_str(), &duration_in_sec_,
471 1e-9)) {
Yabin Cui8a599d72016-07-21 18:32:53 -0700472 LOG(ERROR) << "Invalid duration: " << args[i].c_str();
473 return false;
474 }
Wei Wang539fb882016-09-28 14:42:02 -0700475 } else if (args[i] == "--interval") {
476 if (!NextArgumentOrError(args, &i)) {
477 return false;
478 }
Yabin Cuic0565bb2016-09-29 15:59:33 -0700479 if (!android::base::ParseDouble(args[i].c_str(), &interval_in_ms_,
480 1e-9)) {
Wei Wang539fb882016-09-28 14:42:02 -0700481 LOG(ERROR) << "Invalid interval: " << args[i].c_str();
482 return false;
483 }
Yabin Cui323e9452015-04-20 18:07:17 -0700484 } else if (args[i] == "-e") {
Yabin Cui9759e1b2015-04-28 15:54:13 -0700485 if (!NextArgumentOrError(args, &i)) {
Yabin Cui323e9452015-04-20 18:07:17 -0700486 return false;
487 }
Yabin Cui323e9452015-04-20 18:07:17 -0700488 std::vector<std::string> event_types = android::base::Split(args[i], ",");
489 for (auto& event_type : event_types) {
Yabin Cui877751b2016-06-13 18:03:47 -0700490 if (!event_selection_set_.AddEventType(event_type)) {
Yabin Cui323e9452015-04-20 18:07:17 -0700491 return false;
492 }
493 }
Yabin Cui877751b2016-06-13 18:03:47 -0700494 } else if (args[i] == "--group") {
495 if (!NextArgumentOrError(args, &i)) {
496 return false;
497 }
498 std::vector<std::string> event_types = android::base::Split(args[i], ",");
499 if (!event_selection_set_.AddEventGroup(event_types)) {
500 return false;
501 }
Yabin Cui4be41262015-06-22 14:23:01 -0700502 } else if (args[i] == "--no-inherit") {
503 child_inherit_ = false;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700504 } else if (args[i] == "-o") {
505 if (!NextArgumentOrError(args, &i)) {
506 return false;
507 }
508 output_filename_ = args[i];
Yabin Cuib032de72015-06-17 21:15:09 -0700509 } else if (args[i] == "-p") {
510 if (!NextArgumentOrError(args, &i)) {
511 return false;
512 }
Yabin Cuibc2a1022016-08-29 12:33:17 -0700513 std::set<pid_t> pids;
514 if (!GetValidThreadsFromThreadString(args[i], &pids)) {
Yabin Cuib032de72015-06-17 21:15:09 -0700515 return false;
516 }
Yabin Cuibc2a1022016-08-29 12:33:17 -0700517 event_selection_set_.AddMonitoredProcesses(pids);
Yabin Cuib032de72015-06-17 21:15:09 -0700518 } else if (args[i] == "-t") {
519 if (!NextArgumentOrError(args, &i)) {
520 return false;
521 }
Yabin Cuibc2a1022016-08-29 12:33:17 -0700522 std::set<pid_t> tids;
523 if (!GetValidThreadsFromThreadString(args[i], &tids)) {
Yabin Cuib032de72015-06-17 21:15:09 -0700524 return false;
525 }
Yabin Cuibc2a1022016-08-29 12:33:17 -0700526 event_selection_set_.AddMonitoredThreads(tids);
Yabin Cui323e9452015-04-20 18:07:17 -0700527 } else if (args[i] == "--verbose") {
528 verbose_mode_ = true;
529 } else {
Yabin Cuif79f07e2015-06-01 11:21:37 -0700530 ReportUnknownOption(args, i);
Yabin Cui323e9452015-04-20 18:07:17 -0700531 return false;
532 }
533 }
534
Yabin Cuibc2a1022016-08-29 12:33:17 -0700535 if (system_wide_collection_ && event_selection_set_.HasMonitoredTarget()) {
Yabin Cui877751b2016-06-13 18:03:47 -0700536 LOG(ERROR) << "Stat system wide and existing processes/threads can't be "
537 "used at the same time.";
Yabin Cuib032de72015-06-17 21:15:09 -0700538 return false;
539 }
Yabin Cui8a599d72016-07-21 18:32:53 -0700540 if (system_wide_collection_ && !IsRoot()) {
541 LOG(ERROR) << "System wide profiling needs root privilege.";
542 return false;
543 }
Yabin Cuib032de72015-06-17 21:15:09 -0700544
Yabin Cui8a599d72016-07-21 18:32:53 -0700545 non_option_args->clear();
546 for (; i < args.size(); ++i) {
547 non_option_args->push_back(args[i]);
548 }
Yabin Cui323e9452015-04-20 18:07:17 -0700549 return true;
550}
551
Yabin Cuif79f07e2015-06-01 11:21:37 -0700552bool StatCommand::AddDefaultMeasuredEventTypes() {
Yabin Cui323e9452015-04-20 18:07:17 -0700553 for (auto& name : default_measured_event_types) {
Yabin Cui877751b2016-06-13 18:03:47 -0700554 // It is not an error when some event types in the default list are not
555 // supported by the kernel.
Yabin Cui9fd3cc12015-06-25 17:42:23 -0700556 const EventType* type = FindEventTypeByName(name);
Yabin Cui877751b2016-06-13 18:03:47 -0700557 if (type != nullptr &&
Yabin Cui26968e62017-01-30 11:34:24 -0800558 IsEventAttrSupported(CreateDefaultPerfEventAttr(*type))) {
Yabin Cui877751b2016-06-13 18:03:47 -0700559 if (!event_selection_set_.AddEventType(name)) {
560 return false;
561 }
Yabin Cui9fd3cc12015-06-25 17:42:23 -0700562 }
Yabin Cui323e9452015-04-20 18:07:17 -0700563 }
Yabin Cui877751b2016-06-13 18:03:47 -0700564 if (event_selection_set_.empty()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700565 LOG(ERROR) << "Failed to add any supported default measured types";
566 return false;
567 }
568 return true;
569}
570
Yabin Cui877751b2016-06-13 18:03:47 -0700571void StatCommand::SetEventSelectionFlags() {
Yabin Cui4be41262015-06-22 14:23:01 -0700572 event_selection_set_.SetInherit(child_inherit_);
573}
574
Yabin Cui877751b2016-06-13 18:03:47 -0700575bool StatCommand::ShowCounters(const std::vector<CountersInfo>& counters,
Wei Wang539fb882016-09-28 14:42:02 -0700576 double duration_in_sec, FILE* fp) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700577 if (csv_) {
578 fprintf(fp, "Performance counter statistics,\n");
579 } else {
580 fprintf(fp, "Performance counter statistics:\n\n");
581 }
Yabin Cui323e9452015-04-20 18:07:17 -0700582
Yabin Cui04d08a32015-08-19 15:01:12 -0700583 if (verbose_mode_) {
584 for (auto& counters_info : counters) {
Yabin Cui04d08a32015-08-19 15:01:12 -0700585 for (auto& counter_info : counters_info.counters) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700586 if (csv_) {
Yabin Cui8a599d72016-07-21 18:32:53 -0700587 fprintf(fp, "%s,tid,%d,cpu,%d,count,%" PRIu64 ",time_enabled,%" PRIu64
588 ",time running,%" PRIu64 ",id,%" PRIu64 ",\n",
Yabin Cui003b2452016-09-29 15:32:45 -0700589 counters_info.event_name.c_str(), counter_info.tid,
590 counter_info.cpu, counter_info.counter.value,
591 counter_info.counter.time_enabled,
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700592 counter_info.counter.time_running, counter_info.counter.id);
593 } else {
594 fprintf(fp,
595 "%s(tid %d, cpu %d): count %" PRIu64 ", time_enabled %" PRIu64
596 ", time running %" PRIu64 ", id %" PRIu64 "\n",
Yabin Cui003b2452016-09-29 15:32:45 -0700597 counters_info.event_name.c_str(), counter_info.tid,
598 counter_info.cpu, counter_info.counter.value,
599 counter_info.counter.time_enabled,
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700600 counter_info.counter.time_running, counter_info.counter.id);
601 }
Yabin Cui323e9452015-04-20 18:07:17 -0700602 }
603 }
Yabin Cui04d08a32015-08-19 15:01:12 -0700604 }
Yabin Cui323e9452015-04-20 18:07:17 -0700605
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700606 CounterSummaries summaries(csv_);
Yabin Cui04d08a32015-08-19 15:01:12 -0700607 for (auto& counters_info : counters) {
608 uint64_t value_sum = 0;
609 uint64_t time_enabled_sum = 0;
610 uint64_t time_running_sum = 0;
611 for (auto& counter_info : counters_info.counters) {
Yabin Cui778424b2016-08-24 19:32:55 -0700612 value_sum += counter_info.counter.value;
613 time_enabled_sum += counter_info.counter.time_enabled;
614 time_running_sum += counter_info.counter.time_running;
Yabin Cui9759e1b2015-04-28 15:54:13 -0700615 }
Yabin Cui04d08a32015-08-19 15:01:12 -0700616 double scale = 1.0;
Yabin Cui810d1c52016-05-16 20:07:26 -0700617 if (time_running_sum < time_enabled_sum && time_running_sum != 0) {
618 scale = static_cast<double>(time_enabled_sum) / time_running_sum;
Yabin Cui323e9452015-04-20 18:07:17 -0700619 }
Yabin Cui003b2452016-09-29 15:32:45 -0700620 summaries.AddSummary(
621 CounterSummary(counters_info.event_name, counters_info.event_modifier,
622 counters_info.group_id, value_sum, scale, false, csv_));
Yabin Cui323e9452015-04-20 18:07:17 -0700623 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700624 summaries.AutoGenerateSummaries();
625 summaries.GenerateComments(duration_in_sec);
626 summaries.Show(fp);
Yabin Cui04d08a32015-08-19 15:01:12 -0700627
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700628 if (csv_)
629 fprintf(fp, "Total test time,%lf,seconds,\n", duration_in_sec);
630 else
631 fprintf(fp, "\nTotal test time: %lf seconds.\n", duration_in_sec);
Yabin Cui323e9452015-04-20 18:07:17 -0700632 return true;
633}
634
Yabin Cui877751b2016-06-13 18:03:47 -0700635} // namespace
636
Yabin Cuiff7465c2016-02-25 11:02:30 -0800637void RegisterStatCommand() {
Yabin Cui877751b2016-06-13 18:03:47 -0700638 RegisterCommand("stat",
639 [] { return std::unique_ptr<Command>(new StatCommand); });
Yabin Cuif79f07e2015-06-01 11:21:37 -0700640}