• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
5from metrics import Metric
6from telemetry.value import scalar
7
8class PowerMetric(Metric):
9  """A metric for measuring power usage."""
10
11  def __init__(self):
12    super(PowerMetric, self).__init__()
13    self._browser = None
14    self._running = False
15    self._starting_cpu_stats = None
16    self._results = None
17
18  def __del__(self):
19    # TODO(jeremy): Remove once crbug.com/350841 is fixed.
20    # Don't leave power monitoring processes running on the system.
21    self._StopInternal()
22    parent = super(PowerMetric, self)
23    if hasattr(parent, '__del__'):
24      parent.__del__()
25
26  def _StopInternal(self):
27    """ Stop monitoring power if measurement is running. This function is
28    idempotent."""
29    if not self._running:
30      return
31    self._running = False
32    self._results = self._browser.platform.StopMonitoringPower()
33    if self._results: # StopMonitoringPower() can return None.
34      self._results['cpu_stats'] = (
35          _SubtractCpuStats(self._browser.cpu_stats, self._starting_cpu_stats))
36
37  def Start(self, _, tab):
38    if not tab.browser.platform.CanMonitorPower():
39      return
40
41    self._results = None
42    self._browser = tab.browser
43    self._StopInternal()
44
45    # This line invokes top a few times, call before starting power measurement.
46    self._starting_cpu_stats = self._browser.cpu_stats
47    self._browser.platform.StartMonitoringPower(self._browser)
48    self._running = True
49
50  def Stop(self, _, tab):
51    if not tab.browser.platform.CanMonitorPower():
52      return
53
54    self._StopInternal()
55
56  def AddResults(self, _, results):
57    """Add the collected power data into the results object.
58
59    This function needs to be robust in the face of differing power data on
60    various platforms. Therefore data existence needs to be checked when
61    building up the results. Additionally 0 is a valid value for many of the
62    metrics here which is why there are plenty of checks for 'is not None'
63    below.
64    """
65    if not self._results:
66      return
67
68    energy_consumption_mwh = self._results.get('energy_consumption_mwh')
69    if energy_consumption_mwh is not None:
70      results.AddValue(scalar.ScalarValue(
71          results.current_page, 'energy_consumption_mwh', 'mWh',
72          energy_consumption_mwh))
73
74    component_utilization = self._results.get('component_utilization', {})
75    # GPU Frequency.
76    gpu_power = component_utilization.get('gpu', {})
77    gpu_freq_hz = gpu_power.get('average_frequency_hz')
78    if gpu_freq_hz is not None:
79      results.AddValue(scalar.ScalarValue(
80          results.current_page, 'gpu_average_frequency_hz', 'hz', gpu_freq_hz,
81          important=False))
82
83    # Add idle wakeup numbers for all processes.
84    for (process_type, stats) in self._results.get('cpu_stats', {}).items():
85      trace_name_for_process = 'idle_wakeups_%s' % (process_type.lower())
86      results.AddValue(scalar.ScalarValue(
87          results.current_page, trace_name_for_process, 'count', stats,
88          important=False))
89
90    # Add temperature measurements.
91    whole_package_utilization = component_utilization.get('whole_package', {})
92    board_temperature_c = whole_package_utilization.get('average_temperature_c')
93    if board_temperature_c is not None:
94      results.AddValue(scalar.ScalarValue(
95          results.current_page, 'board_temperature', 'celsius',
96          board_temperature_c, important=False))
97
98    self._results = None
99
100def _SubtractCpuStats(cpu_stats, start_cpu_stats):
101  """Computes number of idle wakeups that occurred over measurement period.
102
103  Each of the two cpu_stats arguments is a dict as returned by the
104  Browser.cpu_stats call.
105
106  Returns:
107    A dict of process type names (Browser, Renderer, etc.) to idle wakeup count
108    over the period recorded by the input.
109  """
110  cpu_delta = {}
111  for process_type in cpu_stats:
112    assert process_type in start_cpu_stats, 'Mismatching process types'
113    # Skip any process_types that are empty.
114    if (not cpu_stats[process_type]) or (not start_cpu_stats[process_type]):
115      continue
116    # Skip if IdleWakeupCount is not present.
117    if (('IdleWakeupCount' not in cpu_stats[process_type]) or
118        ('IdleWakeupCount' not in start_cpu_stats[process_type])):
119      continue
120    idle_wakeup_delta = (cpu_stats[process_type]['IdleWakeupCount'] -
121                        start_cpu_stats[process_type]['IdleWakeupCount'])
122    cpu_delta[process_type] = idle_wakeup_delta
123  return cpu_delta
124