Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1543)

Side by Side Diff: chrome/browser/power_usage_monitor/power_usage_monitor.cc

Issue 2716593006: Remove PowerUsageMonitor. (Closed)
Patch Set: Adjust comment Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/power_usage_monitor/power_usage_monitor.h"
6
7 #include <stddef.h>
8 #include <utility>
9
10 #include "base/bind.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/sys_info.h"
17 #include "content/public/browser/browser_thread.h"
18 #include "content/public/browser/notification_service.h"
19 #include "content/public/browser/notification_source.h"
20 #include "content/public/browser/notification_types.h"
21 #include "content/public/browser/render_process_host.h"
22
23 namespace {
24
25 // Wait this long after power on before enabling power usage monitoring.
26 const int kMinUptimeMinutes = 30;
27
28 // Minimum discharge time after which we collect the discharge rate.
29 const int kMinDischargeMinutes = 30;
30
31 class PowerUsageMonitorSystemInterface
32 : public PowerUsageMonitor::SystemInterface {
33 public:
34 explicit PowerUsageMonitorSystemInterface(PowerUsageMonitor* owner)
35 : power_usage_monitor_(owner), weak_ptr_factory_(this) {}
36 ~PowerUsageMonitorSystemInterface() override {}
37
38 void ScheduleHistogramReport(base::TimeDelta delay) override {
39 content::BrowserThread::PostDelayedTask(
40 content::BrowserThread::UI, FROM_HERE,
41 base::Bind(
42 &PowerUsageMonitorSystemInterface::ReportBatteryLevelHistogram,
43 weak_ptr_factory_.GetWeakPtr(), Now(), delay),
44 delay);
45 }
46
47 void CancelPendingHistogramReports() override {
48 weak_ptr_factory_.InvalidateWeakPtrs();
49 }
50
51 void RecordDischargePercentPerHour(int percent_per_hour) override {
52 UMA_HISTOGRAM_PERCENTAGE("Power.BatteryDischargePercentPerHour",
53 percent_per_hour);
54 }
55
56 base::Time Now() override { return base::Time::Now(); }
57
58 protected:
59 void ReportBatteryLevelHistogram(base::Time start_time,
60 base::TimeDelta discharge_time) {
61 // It's conceivable that the code to cancel pending histogram reports on
62 // system suspend, will only get called after the system has woken up.
63 // To mitigage this, check whether more time has passed than expected and
64 // abort histogram recording in this case.
65
66 // Delayed tasks are subject to timer coalescing and can fire anywhere from
67 // delay -> delay * 1.5) . In most cases, the OS should fire the task
68 // at the next wakeup and not as late as it can.
69 // A threshold of 2 minutes is used, since that should be large enough to
70 // take the slop factor due to coalescing into account.
71 base::TimeDelta threshold =
72 discharge_time + base::TimeDelta::FromMinutes(2);
73 if ((Now() - start_time) > threshold) {
74 return;
75 }
76
77 const std::string histogram_name = base::StringPrintf(
78 "Power.BatteryDischarge_%d", discharge_time.InMinutes());
79 base::HistogramBase* histogram =
80 base::Histogram::FactoryGet(histogram_name, 1, 100, 101,
81 base::Histogram::kUmaTargetedHistogramFlag);
82 double discharge_amount = power_usage_monitor_->discharge_amount();
83 histogram->Add(discharge_amount * 100);
84 }
85
86 private:
87 PowerUsageMonitor* power_usage_monitor_; // Not owned.
88
89 // Used to cancel in progress delayed tasks.
90 base::WeakPtrFactory<PowerUsageMonitorSystemInterface> weak_ptr_factory_;
91 };
92
93 } // namespace
94
95 PowerUsageMonitor::PowerUsageMonitor()
96 : callback_(base::Bind(&PowerUsageMonitor::OnBatteryStatusUpdate,
97 base::Unretained(this))),
98 system_interface_(new PowerUsageMonitorSystemInterface(this)),
99 started_(false),
100 tracking_discharge_(false),
101 on_battery_power_(false),
102 initial_battery_level_(0),
103 current_battery_level_(0) {}
104
105 PowerUsageMonitor::~PowerUsageMonitor() {
106 if (started_)
107 base::PowerMonitor::Get()->RemoveObserver(this);
108 }
109
110 void PowerUsageMonitor::Start() {
111 // Power monitoring may be delayed based on uptime, but renderer process
112 // lifetime tracking needs to start immediately so processes created before
113 // then are accounted for.
114 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
115 content::NotificationService::AllBrowserContextsAndSources());
116 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
117 content::NotificationService::AllBrowserContextsAndSources());
118 subscription_ =
119 device::BatteryStatusService::GetInstance()->AddCallback(callback_);
120
121 // Delay initialization until the system has been up for a while.
122 // This is to mitigate the effect of increased power draw during system start.
123 base::TimeDelta uptime = base::SysInfo::Uptime();
124 base::TimeDelta min_uptime = base::TimeDelta::FromMinutes(kMinUptimeMinutes);
125 if (uptime < min_uptime) {
126 base::TimeDelta delay = min_uptime - uptime;
127 content::BrowserThread::PostDelayedTask(
128 content::BrowserThread::UI, FROM_HERE,
129 base::Bind(&PowerUsageMonitor::StartInternal, base::Unretained(this)),
130 delay);
131 } else {
132 StartInternal();
133 }
134 }
135
136 void PowerUsageMonitor::StartInternal() {
137 DCHECK(!started_);
138 started_ = true;
139
140 // PowerMonitor is used to get suspend/resume notifications.
141 base::PowerMonitor::Get()->AddObserver(this);
142 }
143
144 void PowerUsageMonitor::DischargeStarted(double battery_level) {
145 on_battery_power_ = true;
146
147 // If all browser windows are closed, don't report power metrics since
148 // Chrome's power draw is likely not significant.
149 if (live_renderer_ids_.empty())
150 return;
151
152 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
153 system_interface_->CancelPendingHistogramReports();
154
155 tracking_discharge_ = true;
156 start_discharge_time_ = system_interface_->Now();
157
158 initial_battery_level_ = battery_level;
159 current_battery_level_ = battery_level;
160
161 const int kBatteryReportingIntervalMinutes[] = {5, 15, 30};
162 for (auto reporting_interval : kBatteryReportingIntervalMinutes) {
163 base::TimeDelta delay = base::TimeDelta::FromMinutes(reporting_interval);
164 system_interface_->ScheduleHistogramReport(delay);
165 }
166 }
167
168 void PowerUsageMonitor::WallPowerConnected(double battery_level) {
169 on_battery_power_ = false;
170
171 if (tracking_discharge_) {
172 DCHECK(!start_discharge_time_.is_null());
173 base::TimeDelta discharge_time =
174 system_interface_->Now() - start_discharge_time_;
175
176 if (discharge_time.InMinutes() > kMinDischargeMinutes) {
177 // Record the rate at which the battery discharged over the entire period
178 // the system was on battery power.
179 double discharge_hours = discharge_time.InSecondsF() / 3600.0;
180 int percent_per_hour =
181 floor(((discharge_amount() / discharge_hours) * 100.0) + 0.5);
182 system_interface_->RecordDischargePercentPerHour(percent_per_hour);
183 }
184 }
185
186 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
187 system_interface_->CancelPendingHistogramReports();
188
189 initial_battery_level_ = 0;
190 current_battery_level_ = 0;
191 start_discharge_time_ = base::Time();
192 tracking_discharge_ = false;
193 }
194
195 void PowerUsageMonitor::OnBatteryStatusUpdate(
196 const device::BatteryStatus& status) {
197 bool now_on_battery_power = (status.charging == 0);
198 bool was_on_battery_power = on_battery_power_;
199 double battery_level = status.level;
200
201 if (now_on_battery_power == was_on_battery_power) {
202 if (now_on_battery_power)
203 current_battery_level_ = battery_level;
204 return;
205 } else if (now_on_battery_power) { // Wall power disconnected.
206 DischargeStarted(battery_level);
207 } else { // Wall power connected.
208 WallPowerConnected(battery_level);
209 }
210 }
211
212 void PowerUsageMonitor::OnRenderProcessNotification(int type, int rph_id) {
213 size_t previous_num_live_renderers = live_renderer_ids_.size();
214
215 if (type == content::NOTIFICATION_RENDERER_PROCESS_CREATED) {
216 live_renderer_ids_.insert(rph_id);
217 } else if (type == content::NOTIFICATION_RENDERER_PROCESS_CLOSED) {
218 live_renderer_ids_.erase(rph_id);
219 } else {
220 NOTREACHED() << "Unexpected notification type: " << type;
221 }
222
223 if (live_renderer_ids_.empty() && previous_num_live_renderers != 0) {
224 // All render processes have died.
225 CancelPendingHistogramReporting();
226 tracking_discharge_ = false;
227 }
228 }
229
230 void PowerUsageMonitor::SetSystemInterfaceForTest(
231 std::unique_ptr<SystemInterface> system_interface) {
232 system_interface_ = std::move(system_interface);
233 }
234
235 void PowerUsageMonitor::OnPowerStateChange(bool on_battery_power) {}
236
237 void PowerUsageMonitor::OnResume() {}
238
239 void PowerUsageMonitor::OnSuspend() {
240 CancelPendingHistogramReporting();
241 }
242
243 void PowerUsageMonitor::Observe(int type,
244 const content::NotificationSource& source,
245 const content::NotificationDetails& details) {
246 content::RenderProcessHost* rph =
247 content::Source<content::RenderProcessHost>(source).ptr();
248 OnRenderProcessNotification(type, rph->GetID());
249 }
250
251 void PowerUsageMonitor::CancelPendingHistogramReporting() {
252 // Cancel any in-progress histogram reports and reporting of discharge UMA.
253 system_interface_->CancelPendingHistogramReports();
254 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698