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

Side by Side Diff: content/browser/power_usage_monitor_impl.cc

Issue 560553005: Battery impact UMA (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Additional style fixes Created 6 years, 1 month 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 "content/browser/power_usage_monitor_impl.h"
6
7 #include "base/bind.h"
8 #include "base/lazy_instance.h"
9 #include "base/logging.h"
10 #include "base/macros.h"
11 #include "base/metrics/histogram.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/sys_info.h"
14 #include "content/public/browser/browser_thread.h"
15 #include "content/public/browser/notification_service.h"
16 #include "content/public/browser/notification_source.h"
17 #include "content/public/browser/notification_types.h"
18 #include "content/public/browser/power_usage_monitor.h"
19 #include "content/public/browser/render_process_host.h"
20
21 namespace content {
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 // Battery life to to use when calculating discharge rate.
32 // The significance of this number is the discharge time to use as an upper
33 // bound when calculating discharge rate i.e. if the battery didn't discharge
34 // after this much time then power draw is too low to be of interest.
35 const int kLongBatteryLifeMinutes = 8 * 60;
36
37 class PowerUsageMonitorSystemInterface
38 : public PowerUsageMonitor::SystemInterface {
39 public:
40 explicit PowerUsageMonitorSystemInterface(PowerUsageMonitor* owner)
41 : power_usage_monitor_(owner),
42 weak_ptr_factory_(this) {}
43 ~PowerUsageMonitorSystemInterface() override {}
44
45 void ScheduleHistogramReport(base::TimeDelta delay) override {
46 BrowserThread::PostDelayedTask(
47 BrowserThread::UI,
48 FROM_HERE,
49 base::Bind(
50 &PowerUsageMonitorSystemInterface::ReportBatteryLevelHistogram,
51 weak_ptr_factory_.GetWeakPtr(),
52 Now(),
53 delay),
54 delay);
55 }
56
57 void CancelPendingHistogramReports() override {
58 weak_ptr_factory_.InvalidateWeakPtrs();
59 }
60
61 void RecordDischargeRate(int discharge_rate) override {
62 UMA_HISTOGRAM_PERCENTAGE("Power.BatteryDischargeRateWhenUnplugged",
63 discharge_rate);
64 }
65
66 base::Time Now() override { return base::Time::Now(); }
67
68 protected:
69 void ReportBatteryLevelHistogram(base::Time start_time,
70 base::TimeDelta discharge_time) {
71 // It's conceivable that the code to cancel pending histogram reports on
72 // system suspend, will only get called after the system has woken up.
73 // To mitigage this, check whether more time has passed than expected and
74 // abort histogram recording in this case.
75
76 // Delayed tasks are subject to timer coalescing and can fire anywhere from
77 // delay -> delay * 1.5) . In most cases, the OS should fire the task
78 // at the next wakeup and not as late as it can.
79 // A threshold of 2 minutes is used, since that should be large enough to
80 // take the slop factor due to coalescing into account.
81 base::TimeDelta threshold = discharge_time +
82 base::TimeDelta::FromMinutes(2);
83 if ((Now() - start_time) > threshold) {
84 UMA_HISTOGRAM_BOOLEAN("Power.BatteryDischargeReportsCancelled", true);
85 return;
86 }
87
88 const std::string histogram_name = base::StringPrintf(
89 "Power.BatteryDischarge_%d", discharge_time.InMinutes());
90 base::HistogramBase* histogram =
91 base::Histogram::FactoryGet(histogram_name,
92 1,
93 100,
94 101,
95 base::Histogram::kUmaTargetedHistogramFlag);
96 double discharge_amount = power_usage_monitor_->discharge_amount();
97 histogram->Add(discharge_amount * 100);
98 }
99
100 private:
101 PowerUsageMonitor* power_usage_monitor_; // Not owned.
102
103 // Used to cancel in progress delayed tasks.
104 base::WeakPtrFactory<PowerUsageMonitorSystemInterface> weak_ptr_factory_;
105 };
106
107 } // namespace
108
109 void StartPowerUsageMonitor() {
110 static base::LazyInstance<PowerUsageMonitor>::Leaky monitor =
111 LAZY_INSTANCE_INITIALIZER;
112 monitor.Get().Start();
113 }
114
115 PowerUsageMonitor::PowerUsageMonitor()
116 : callback_(base::Bind(&PowerUsageMonitor::OnBatteryStatusUpdate,
117 base::Unretained(this))),
118 system_interface_(new PowerUsageMonitorSystemInterface(this)),
119 started_(false),
120 tracking_discharge_(false),
121 on_battery_power_(false),
122 initial_battery_level_(0),
123 current_battery_level_(0) {
124 }
125
126 PowerUsageMonitor::~PowerUsageMonitor() {
127 if (started_)
128 base::PowerMonitor::Get()->RemoveObserver(this);
129 }
130
131 void PowerUsageMonitor::Start() {
132 // Delay initialization until the system has been up for a while.
133 // This is to mitigate the effect of increased power draw during system start.
134 base::TimeDelta uptime =
135 base::TimeDelta::FromMilliseconds(base::SysInfo::Uptime());
136 if (uptime.InMinutes() < kMinUptimeMinutes) {
137 base::TimeDelta delay =
138 base::TimeDelta::FromMinutes(kMinUptimeMinutes - uptime.InMinutes());
Daniel Erat 2014/11/05 17:17:20 just do base::TimeDelta::FromMinutes(kMinUptimeMin
jeremy 2014/11/06 17:12:56 Done.
139 BrowserThread::PostDelayedTask(
140 BrowserThread::UI,
141 FROM_HERE,
142 base::Bind(&PowerUsageMonitor::StartInternal, base::Unretained(this)),
143 delay);
144 } else {
145 StartInternal();
146 }
147 }
148
149 void PowerUsageMonitor::StartInternal() {
150 CHECK(!started_);
Avi (use Gerrit) 2014/11/05 20:56:28 Why all the CHECKs rather than DCHECKs? That's not
jeremy 2014/11/06 17:12:56 Done.
151 started_ = true;
152
153 // PowerMonitor is used to get suspend/resume notifications.
154 base::PowerMonitor::Get()->AddObserver(this);
155
156 registrar_.Add(this,
157 NOTIFICATION_RENDERER_PROCESS_CREATED,
158 NotificationService::AllBrowserContextsAndSources());
159 registrar_.Add(this,
160 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
161 NotificationService::AllBrowserContextsAndSources());
162 registrar_.Add(this,
163 NOTIFICATION_RENDERER_PROCESS_CLOSED,
164 NotificationService::AllBrowserContextsAndSources());
165 subscription_ =
166 device::BatteryStatusService::GetInstance()->AddCallback(callback_);
167 }
168
169 void PowerUsageMonitor::DischargeStarted(double battery_level) {
170 on_battery_power_ = true;
171
172 // If all browser windows are closed, don't report power metrics since
173 // Chrome's power draw is likely not significant.
174 if (live_renderer_ids_.empty())
175 return;
176
177 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
178 system_interface_->CancelPendingHistogramReports();
179
180 tracking_discharge_ = true;
181 start_discharge_time_ = system_interface_->Now();
182
183 initial_battery_level_ = battery_level;
184 current_battery_level_ = battery_level;
185
186 const int kBatteryReportingIntervalMinutes[] = {5, 15, 30};
187 for (auto reporting_interval : kBatteryReportingIntervalMinutes) {
188 base::TimeDelta delay = base::TimeDelta::FromMinutes(reporting_interval);
189 system_interface_->ScheduleHistogramReport(delay);
190 }
191 }
192
193 void PowerUsageMonitor::WallPowerConnected(double battery_level) {
194 on_battery_power_ = false;
195
196 if (tracking_discharge_) {
197 CHECK(!start_discharge_time_.is_null());
198 base::TimeDelta discharge_time =
199 system_interface_->Now() - start_discharge_time_;
200
201 if (discharge_time.InMinutes() > kMinDischargeMinutes) {
202 // discharge_rate is adjusted so that
203 // 1.0 = fully discharged in a short amt of time.
Avi (use Gerrit) 2014/11/05 20:56:29 s/amt/amount/
jeremy 2014/11/06 17:12:56 Done.
204 // 0.0 = fully discharged over kLongBatteryLifeMinutes minutes.
205 double scaling_factor =
206 (1.0 - discharge_time.InMinutes()/kLongBatteryLifeMinutes);
207 scaling_factor = std::max(std::min(scaling_factor, 1.0), 0.0);
208 double discharge_rate = discharge_amount() * scaling_factor;
209 system_interface_->RecordDischargeRate(discharge_rate * 100.0);
210 }
211 }
212
213 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
214 system_interface_->CancelPendingHistogramReports();
215
216 initial_battery_level_ = 0;
217 current_battery_level_ = 0;
218 start_discharge_time_ = base::Time();
219 tracking_discharge_ = false;
220 }
221
222 void PowerUsageMonitor::OnBatteryStatusUpdate(
223 const device::BatteryStatus& status) {
224 bool now_on_battery_power = (status.charging == 0);
225 bool was_on_battery_power = on_battery_power_;
226 double battery_level = status.level;
227
228 if (now_on_battery_power == was_on_battery_power) {
229 if (now_on_battery_power)
230 current_battery_level_ = battery_level;
231 return;
232 } else if (now_on_battery_power) { // Wall power disconnected.
233 DischargeStarted(battery_level);
234 } else { // Wall power connected.
235 WallPowerConnected(battery_level);
236 }
237 }
238
239 void PowerUsageMonitor::OnRenderProcessNotification(int type, int rph_id) {
240 size_t previous_num_live_renderers = live_renderer_ids_.size();
241
242 if (type == NOTIFICATION_RENDERER_PROCESS_CREATED) {
243 live_renderer_ids_.insert(rph_id);
244 } else if (type == NOTIFICATION_RENDERER_PROCESS_TERMINATED ||
245 type == NOTIFICATION_RENDERER_PROCESS_CLOSED) {
Avi (use Gerrit) 2014/11/05 20:56:28 You shouldn't need all of those. NOTIFICATION_REN
jeremy 2014/11/06 17:12:56 Done.
246 live_renderer_ids_.erase(rph_id);
247 } else {
248 NOTREACHED() << "Unexpected notification type: " << type;
249 }
250
251 if (live_renderer_ids_.empty() && previous_num_live_renderers != 0) {
252 // All render processes have died.
253 CancelPendingHistogramReporting();
254 tracking_discharge_ = false;
255 }
256
257 }
258
259 void PowerUsageMonitor::SetSystemInterfaceForTest(
260 scoped_ptr<SystemInterface> interface) {
261 system_interface_ = interface.Pass();
262 }
263
264 void PowerUsageMonitor::OnPowerStateChange(bool on_battery_power) {
265 }
266
267 void PowerUsageMonitor::OnResume() {
268 }
269
270 void PowerUsageMonitor::OnSuspend() {
271 CancelPendingHistogramReporting();
272 }
273
274 void PowerUsageMonitor::Observe(int type,
275 const NotificationSource& source,
276 const NotificationDetails& details) {
277 RenderProcessHost* rph = Source<RenderProcessHost>(source).ptr();
278 OnRenderProcessNotification(type, rph->GetID());
279 }
280
281 void PowerUsageMonitor::CancelPendingHistogramReporting() {
282 // Cancel any in-progress histogram reports and reporting of discharge UMA.
283 system_interface_->CancelPendingHistogramReports();
284 }
285
286 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698