File: cpu_usage_collector.cc

package info (click to toggle)
android-platform-system-core 1%3A7.0.0%2Br33-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,464 kB
  • sloc: cpp: 96,742; ansic: 39,563; asm: 3,482; python: 1,571; sh: 666; lex: 311; java: 169; makefile: 65; xml: 19
file content (126 lines) | stat: -rw-r--r-- 4,362 bytes parent folder | download
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
/*
 * 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 "collectors/cpu_usage_collector.h"

#include <base/bind.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/message_loop/message_loop.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/string_split.h>
#include <base/strings/string_util.h>
#include <base/sys_info.h>

#include "metrics/metrics_library.h"

namespace {

const char kCpuUsagePercent[] = "Platform.CpuUsage.Percent";
const char kMetricsProcStatFileName[] = "/proc/stat";
const int kMetricsProcStatFirstLineItemsCount = 11;

// Collect every minute.
const int kCollectionIntervalSecs = 60;

}  // namespace

using base::TimeDelta;

CpuUsageCollector::CpuUsageCollector(MetricsLibraryInterface* metrics_library) {
  CHECK(metrics_library);
  metrics_lib_ = metrics_library;
  collect_interval_ = TimeDelta::FromSeconds(kCollectionIntervalSecs);
}

void CpuUsageCollector::Init() {
  num_cpu_ = base::SysInfo::NumberOfProcessors();

  // Get ticks per second (HZ) on this system.
  // Sysconf cannot fail, so no sanity checks are needed.
  ticks_per_second_ = sysconf(_SC_CLK_TCK);
  CHECK_GT(ticks_per_second_, uint64_t(0))
      << "Number of ticks per seconds should be positive.";

  latest_cpu_use_ = GetCumulativeCpuUse();
}

void CpuUsageCollector::CollectCallback() {
  Collect();
  Schedule();
}

void CpuUsageCollector::Schedule() {
  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
      base::Bind(&CpuUsageCollector::CollectCallback, base::Unretained(this)),
      collect_interval_);
}

void CpuUsageCollector::Collect() {
  TimeDelta cpu_use = GetCumulativeCpuUse();
  TimeDelta diff_per_cpu = (cpu_use - latest_cpu_use_) / num_cpu_;
  latest_cpu_use_ = cpu_use;

  // Report the cpu usage as a percentage of the total cpu usage possible.
  int percent_use = diff_per_cpu.InMilliseconds() * 100 /
      (kCollectionIntervalSecs * 1000);

  metrics_lib_->SendEnumToUMA(kCpuUsagePercent, percent_use, 101);
}

TimeDelta CpuUsageCollector::GetCumulativeCpuUse() {
  base::FilePath proc_stat_path(kMetricsProcStatFileName);
  std::string proc_stat_string;
  if (!base::ReadFileToString(proc_stat_path, &proc_stat_string)) {
    LOG(WARNING) << "cannot open " << kMetricsProcStatFileName;
    return TimeDelta();
  }

  uint64_t user_ticks, user_nice_ticks, system_ticks;
  if (!ParseProcStat(proc_stat_string, &user_ticks, &user_nice_ticks,
                     &system_ticks)) {
    return TimeDelta();
  }

  uint64_t total = user_ticks + user_nice_ticks + system_ticks;
  return TimeDelta::FromMicroseconds(
      total * 1000 * 1000 / ticks_per_second_);
}

bool CpuUsageCollector::ParseProcStat(const std::string& stat_content,
                                      uint64_t *user_ticks,
                                      uint64_t *user_nice_ticks,
                                      uint64_t *system_ticks) {
  std::vector<std::string> proc_stat_lines = base::SplitString(
      stat_content, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  if (proc_stat_lines.empty()) {
    LOG(WARNING) << "No lines found in " << kMetricsProcStatFileName;
    return false;
  }
  std::vector<std::string> proc_stat_totals =
      base::SplitString(proc_stat_lines[0], base::kWhitespaceASCII,
                        base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);

  if (proc_stat_totals.size() != kMetricsProcStatFirstLineItemsCount ||
      proc_stat_totals[0] != "cpu" ||
      !base::StringToUint64(proc_stat_totals[1], user_ticks) ||
      !base::StringToUint64(proc_stat_totals[2], user_nice_ticks) ||
      !base::StringToUint64(proc_stat_totals[3], system_ticks)) {
    LOG(WARNING) << "cannot parse first line: " << proc_stat_lines[0];
    return false;
  }
  return true;
}