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 telemetry.value import improvement_direction
6from telemetry.value import list_of_scalar_values
7from telemetry.web_perf.metrics import timeline_based_metric
8
9
10class _SingleEventMetric(timeline_based_metric.TimelineBasedMetric):
11  """Reports directly durations of specific trace events that start during the
12  user interaction.
13  """
14
15  def __init__(self, trace_event_name, metric_name, metric_description=None):
16    super(_SingleEventMetric, self).__init__()
17    self._TRACE_EVENT_NAME = trace_event_name
18    self._metric_name = metric_name
19    self._metric_description = metric_description
20
21  def AddResults(self, model, renderer_thread, interactions, results):
22    del model  # unused
23    assert interactions
24    self._AddResultsInternal(renderer_thread.parent.IterAllSlices(),
25                             interactions, results)
26
27  def _AddResultsInternal(self, events, interactions, results):
28    events_found = []
29    for event in events:
30      if (event.name == self._TRACE_EVENT_NAME) and any(
31              interaction.start <= event.start <= interaction.end
32              for interaction in interactions):
33        if event.has_thread_timestamps:
34          events_found.append(event.thread_duration)
35        else:
36          events_found.append(event.duration)
37    if not events_found:
38      return
39    results.AddValue(list_of_scalar_values.ListOfScalarValues(
40      page=results.current_page,
41      tir_label=interactions[0].label,
42      name=self._metric_name,
43      units='ms',
44      values=events_found,
45      description=self._metric_description,
46      improvement_direction=improvement_direction.DOWN))
47