summaryrefslogtreecommitdiff
path: root/simpleperf/cmd_stat.cpp
blob: 16af81e67f4dd7ba2be1a426c07523e292452cda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <inttypes.h>
#include <stdio.h>
#include <chrono>
#include <string>
#include <vector>

#include <base/logging.h>
#include <base/strings.h>

#include "command.h"
#include "environment.h"
#include "event_selection_set.h"
#include "event_type.h"
#include "perf_event.h"
#include "utils.h"
#include "workload.h"

static std::vector<std::string> default_measured_event_types{
    "cpu-cycles",   "stalled-cycles-frontend", "stalled-cycles-backend",
    "instructions", "branch-instructions",     "branch-misses",
    "task-clock",   "context-switches",        "page-faults",
};

class StatCommandImpl {
 public:
  StatCommandImpl() : verbose_mode_(false), system_wide_collection_(false) {
  }

  bool Run(const std::vector<std::string>& args);

 private:
  bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args);
  bool AddMeasuredEventType(const std::string& event_type_name, bool report_unsupported_type = true);
  bool AddDefaultMeasuredEventTypes();
  bool ShowCounters(const std::map<const EventType*, std::vector<PerfCounter>>& counters_map,
                    std::chrono::steady_clock::duration counting_duration);

  EventSelectionSet event_selection_set_;
  bool verbose_mode_;
  bool system_wide_collection_;
};

bool StatCommandImpl::Run(const std::vector<std::string>& args) {
  // 1. Parse options.
  std::vector<std::string> workload_args;
  if (!ParseOptions(args, &workload_args)) {
    return false;
  }

  // 2. Add default measured event types.
  if (event_selection_set_.Empty()) {
    if (!AddDefaultMeasuredEventTypes()) {
      return false;
    }
  }

  // 3. Create workload.
  if (workload_args.empty()) {
    // TODO: change default workload to sleep 99999, and run stat until Ctrl-C.
    workload_args = std::vector<std::string>({"sleep", "1"});
  }
  std::unique_ptr<Workload> workload = Workload::CreateWorkload(workload_args);
  if (workload == nullptr) {
    return false;
  }

  // 4. Open perf_event_files.
  if (system_wide_collection_) {
    if (!event_selection_set_.OpenEventFilesForAllCpus()) {
      return false;
    }
  } else {
    event_selection_set_.EnableOnExec();
    if (!event_selection_set_.OpenEventFilesForProcess(workload->GetPid())) {
      return false;
    }
  }

  // 5. Count events while workload running.
  auto start_time = std::chrono::steady_clock::now();
  // If monitoring only one process, we use the enable_on_exec flag, and don't need to start
  // counting manually.
  if (system_wide_collection_) {
    if (!event_selection_set_.EnableEvents()) {
      return false;
    }
  }
  if (!workload->Start()) {
    return false;
  }
  workload->WaitFinish();
  auto end_time = std::chrono::steady_clock::now();

  // 6. Read and print counters.
  std::map<const EventType*, std::vector<PerfCounter>> counters_map;
  if (!event_selection_set_.ReadCounters(&counters_map)) {
    return false;
  }
  if (!ShowCounters(counters_map, end_time - start_time)) {
    return false;
  }
  return true;
}

bool StatCommandImpl::ParseOptions(const std::vector<std::string>& args,
                                   std::vector<std::string>* non_option_args) {
  size_t i;
  for (i = 1; i < args.size() && args[i].size() > 0 && args[i][0] == '-'; ++i) {
    if (args[i] == "-a") {
      system_wide_collection_ = true;
    } else if (args[i] == "-e") {
      if (!NextArgumentOrError(args, &i)) {
        return false;
      }
      std::vector<std::string> event_types = android::base::Split(args[i], ",");
      for (auto& event_type : event_types) {
        if (!AddMeasuredEventType(event_type)) {
          return false;
        }
      }
    } else if (args[i] == "--verbose") {
      verbose_mode_ = true;
    } else {
      LOG(ERROR) << "Unknown option for stat command: " << args[i];
      LOG(ERROR) << "Try `simpleperf help stat`";
      return false;
    }
  }

  if (non_option_args != nullptr) {
    non_option_args->clear();
    for (; i < args.size(); ++i) {
      non_option_args->push_back(args[i]);
    }
  }
  return true;
}

bool StatCommandImpl::AddMeasuredEventType(const std::string& event_type_name,
                                           bool report_unsupported_type) {
  const EventType* event_type =
      EventTypeFactory::FindEventTypeByName(event_type_name, report_unsupported_type);
  if (event_type == nullptr) {
    return false;
  }
  event_selection_set_.AddEventType(*event_type);
  return true;
}

bool StatCommandImpl::AddDefaultMeasuredEventTypes() {
  for (auto& name : default_measured_event_types) {
    // It is not an error when some event types in the default list are not supported by the kernel.
    AddMeasuredEventType(name, false);
  }
  if (event_selection_set_.Empty()) {
    LOG(ERROR) << "Failed to add any supported default measured types";
    return false;
  }
  return true;
}

bool StatCommandImpl::ShowCounters(
    const std::map<const EventType*, std::vector<PerfCounter>>& counters_map,
    std::chrono::steady_clock::duration counting_duration) {
  printf("Performance counter statistics:\n\n");

  for (auto& pair : counters_map) {
    auto& event_type = pair.first;
    auto& counters = pair.second;
    if (verbose_mode_) {
      for (auto& counter : counters) {
        printf("%s: value %'" PRId64 ", time_enabled %" PRId64 ", time_running %" PRId64
               ", id %" PRId64 "\n",
               event_selection_set_.FindEventFileNameById(counter.id).c_str(), counter.value,
               counter.time_enabled, counter.time_running, counter.id);
      }
    }

    PerfCounter sum_counter;
    memset(&sum_counter, 0, sizeof(sum_counter));
    for (auto& counter : counters) {
      sum_counter.value += counter.value;
      sum_counter.time_enabled += counter.time_enabled;
      sum_counter.time_running += counter.time_running;
    }
    bool scaled = false;
    int64_t scaled_count = sum_counter.value;
    if (sum_counter.time_running < sum_counter.time_enabled) {
      if (sum_counter.time_running == 0) {
        scaled_count = 0;
      } else {
        scaled = true;
        scaled_count = static_cast<int64_t>(static_cast<double>(sum_counter.value) *
                                            sum_counter.time_enabled / sum_counter.time_running);
      }
    }
    printf("%'30" PRId64 "%s  %s\n", scaled_count, scaled ? "(scaled)" : "       ",
           event_type->name.c_str());
  }
  printf("\nTotal test time: %lf seconds.\n",
         std::chrono::duration_cast<std::chrono::duration<double>>(counting_duration).count());
  return true;
}

class StatCommand : public Command {
 public:
  StatCommand()
      : Command("stat", "gather performance counter information",
                "Usage: simpleperf stat [options] [command [command-args]]\n"
                "    Gather performance counter information of running [command]. If [command]\n"
                "    is not specified, sleep 1 is used instead.\n\n"
                "    -a           Collect system-wide information.\n"
                "    -e event1,event2,... Select the event list to count. Use `simpleperf list`\n"
                "                         to find all possible event names.\n"
                "    --verbose    Show result in verbose mode.\n") {
  }

  bool Run(const std::vector<std::string>& args) override {
    // Keep the implementation in StatCommandImpl, so the resources used are cleaned up when the
    // command finishes. This is useful when we need to call some commands multiple times, like
    // in unit tests.
    StatCommandImpl impl;
    return impl.Run(args);
  }
};

StatCommand stat_command;