Roll DEPS for PDFium to 19ae17578f99621100a26dac3e2c7c3dbf7c7cd1
[chromium-blink-merge.git] / content / browser / power_usage_monitor_impl.cc
blobfb294f3e0ca30e84a7cc1b599a2bb2a9f1a04cbd
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.
5 #include "content/browser/power_usage_monitor_impl.h"
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"
21 namespace content {
23 namespace {
25 // Wait this long after power on before enabling power usage monitoring.
26 const int kMinUptimeMinutes = 30;
28 // Minimum discharge time after which we collect the discharge rate.
29 const int kMinDischargeMinutes = 30;
31 class PowerUsageMonitorSystemInterface
32 : public PowerUsageMonitor::SystemInterface {
33 public:
34 explicit PowerUsageMonitorSystemInterface(PowerUsageMonitor* owner)
35 : power_usage_monitor_(owner),
36 weak_ptr_factory_(this) {}
37 ~PowerUsageMonitorSystemInterface() override {}
39 void ScheduleHistogramReport(base::TimeDelta delay) override {
40 BrowserThread::PostDelayedTask(
41 BrowserThread::UI,
42 FROM_HERE,
43 base::Bind(
44 &PowerUsageMonitorSystemInterface::ReportBatteryLevelHistogram,
45 weak_ptr_factory_.GetWeakPtr(),
46 Now(),
47 delay),
48 delay);
51 void CancelPendingHistogramReports() override {
52 weak_ptr_factory_.InvalidateWeakPtrs();
55 void RecordDischargePercentPerHour(int percent_per_hour) override {
56 UMA_HISTOGRAM_PERCENTAGE("Power.BatteryDischargePercentPerHour",
57 percent_per_hour);
60 base::Time Now() override { return base::Time::Now(); }
62 protected:
63 void ReportBatteryLevelHistogram(base::Time start_time,
64 base::TimeDelta discharge_time) {
65 // It's conceivable that the code to cancel pending histogram reports on
66 // system suspend, will only get called after the system has woken up.
67 // To mitigage this, check whether more time has passed than expected and
68 // abort histogram recording in this case.
70 // Delayed tasks are subject to timer coalescing and can fire anywhere from
71 // delay -> delay * 1.5) . In most cases, the OS should fire the task
72 // at the next wakeup and not as late as it can.
73 // A threshold of 2 minutes is used, since that should be large enough to
74 // take the slop factor due to coalescing into account.
75 base::TimeDelta threshold = discharge_time +
76 base::TimeDelta::FromMinutes(2);
77 if ((Now() - start_time) > threshold) {
78 return;
81 const std::string histogram_name = base::StringPrintf(
82 "Power.BatteryDischarge_%d", discharge_time.InMinutes());
83 base::HistogramBase* histogram =
84 base::Histogram::FactoryGet(histogram_name,
86 100,
87 101,
88 base::Histogram::kUmaTargetedHistogramFlag);
89 double discharge_amount = power_usage_monitor_->discharge_amount();
90 histogram->Add(discharge_amount * 100);
93 private:
94 PowerUsageMonitor* power_usage_monitor_; // Not owned.
96 // Used to cancel in progress delayed tasks.
97 base::WeakPtrFactory<PowerUsageMonitorSystemInterface> weak_ptr_factory_;
100 } // namespace
102 void StartPowerUsageMonitor() {
103 static base::LazyInstance<PowerUsageMonitor>::Leaky monitor =
104 LAZY_INSTANCE_INITIALIZER;
105 monitor.Get().Start();
108 PowerUsageMonitor::PowerUsageMonitor()
109 : callback_(base::Bind(&PowerUsageMonitor::OnBatteryStatusUpdate,
110 base::Unretained(this))),
111 system_interface_(new PowerUsageMonitorSystemInterface(this)),
112 started_(false),
113 tracking_discharge_(false),
114 on_battery_power_(false),
115 initial_battery_level_(0),
116 current_battery_level_(0) {
119 PowerUsageMonitor::~PowerUsageMonitor() {
120 if (started_)
121 base::PowerMonitor::Get()->RemoveObserver(this);
124 void PowerUsageMonitor::Start() {
125 // Power monitoring may be delayed based on uptime, but renderer process
126 // lifetime tracking needs to start immediately so processes created before
127 // then are accounted for.
128 registrar_.Add(this,
129 NOTIFICATION_RENDERER_PROCESS_CREATED,
130 NotificationService::AllBrowserContextsAndSources());
131 registrar_.Add(this,
132 NOTIFICATION_RENDERER_PROCESS_CLOSED,
133 NotificationService::AllBrowserContextsAndSources());
134 subscription_ =
135 device::BatteryStatusService::GetInstance()->AddCallback(callback_);
137 // Delay initialization until the system has been up for a while.
138 // This is to mitigate the effect of increased power draw during system start.
139 base::TimeDelta uptime =
140 base::TimeDelta::FromMilliseconds(base::SysInfo::Uptime());
141 base::TimeDelta min_uptime = base::TimeDelta::FromMinutes(kMinUptimeMinutes);
142 if (uptime < min_uptime) {
143 base::TimeDelta delay = min_uptime - uptime;
144 BrowserThread::PostDelayedTask(
145 BrowserThread::UI,
146 FROM_HERE,
147 base::Bind(&PowerUsageMonitor::StartInternal, base::Unretained(this)),
148 delay);
149 } else {
150 StartInternal();
154 void PowerUsageMonitor::StartInternal() {
155 DCHECK(!started_);
156 started_ = true;
158 // PowerMonitor is used to get suspend/resume notifications.
159 base::PowerMonitor::Get()->AddObserver(this);
162 void PowerUsageMonitor::DischargeStarted(double battery_level) {
163 on_battery_power_ = true;
165 // If all browser windows are closed, don't report power metrics since
166 // Chrome's power draw is likely not significant.
167 if (live_renderer_ids_.empty())
168 return;
170 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
171 system_interface_->CancelPendingHistogramReports();
173 tracking_discharge_ = true;
174 start_discharge_time_ = system_interface_->Now();
176 initial_battery_level_ = battery_level;
177 current_battery_level_ = battery_level;
179 const int kBatteryReportingIntervalMinutes[] = {5, 15, 30};
180 for (auto reporting_interval : kBatteryReportingIntervalMinutes) {
181 base::TimeDelta delay = base::TimeDelta::FromMinutes(reporting_interval);
182 system_interface_->ScheduleHistogramReport(delay);
186 void PowerUsageMonitor::WallPowerConnected(double battery_level) {
187 on_battery_power_ = false;
189 if (tracking_discharge_) {
190 DCHECK(!start_discharge_time_.is_null());
191 base::TimeDelta discharge_time =
192 system_interface_->Now() - start_discharge_time_;
194 if (discharge_time.InMinutes() > kMinDischargeMinutes) {
195 // Record the rate at which the battery discharged over the entire period
196 // the system was on battery power.
197 double discharge_hours = discharge_time.InSecondsF() / 3600.0;
198 int percent_per_hour =
199 floor(((discharge_amount() / discharge_hours) * 100.0) + 0.5);
200 system_interface_->RecordDischargePercentPerHour(percent_per_hour);
204 // Cancel any in-progress ReportBatteryLevelHistogram() calls.
205 system_interface_->CancelPendingHistogramReports();
207 initial_battery_level_ = 0;
208 current_battery_level_ = 0;
209 start_discharge_time_ = base::Time();
210 tracking_discharge_ = false;
213 void PowerUsageMonitor::OnBatteryStatusUpdate(
214 const device::BatteryStatus& status) {
215 bool now_on_battery_power = (status.charging == 0);
216 bool was_on_battery_power = on_battery_power_;
217 double battery_level = status.level;
219 if (now_on_battery_power == was_on_battery_power) {
220 if (now_on_battery_power)
221 current_battery_level_ = battery_level;
222 return;
223 } else if (now_on_battery_power) { // Wall power disconnected.
224 DischargeStarted(battery_level);
225 } else { // Wall power connected.
226 WallPowerConnected(battery_level);
230 void PowerUsageMonitor::OnRenderProcessNotification(int type, int rph_id) {
231 size_t previous_num_live_renderers = live_renderer_ids_.size();
233 if (type == NOTIFICATION_RENDERER_PROCESS_CREATED) {
234 live_renderer_ids_.insert(rph_id);
235 } else if (type == NOTIFICATION_RENDERER_PROCESS_CLOSED) {
236 live_renderer_ids_.erase(rph_id);
237 } else {
238 NOTREACHED() << "Unexpected notification type: " << type;
241 if (live_renderer_ids_.empty() && previous_num_live_renderers != 0) {
242 // All render processes have died.
243 CancelPendingHistogramReporting();
244 tracking_discharge_ = false;
249 void PowerUsageMonitor::SetSystemInterfaceForTest(
250 scoped_ptr<SystemInterface> interface) {
251 system_interface_ = interface.Pass();
254 void PowerUsageMonitor::OnPowerStateChange(bool on_battery_power) {
257 void PowerUsageMonitor::OnResume() {
260 void PowerUsageMonitor::OnSuspend() {
261 CancelPendingHistogramReporting();
264 void PowerUsageMonitor::Observe(int type,
265 const NotificationSource& source,
266 const NotificationDetails& details) {
267 RenderProcessHost* rph = Source<RenderProcessHost>(source).ptr();
268 OnRenderProcessNotification(type, rph->GetID());
271 void PowerUsageMonitor::CancelPendingHistogramReporting() {
272 // Cancel any in-progress histogram reports and reporting of discharge UMA.
273 system_interface_->CancelPendingHistogramReports();
276 } // namespace content