summaryrefslogtreecommitdiffstats
path: root/chromium/third_party/catapult/tracing/tracing/metrics/android_startup_metric.html
blob: 702cdbf5feaac58fb816cb0ed55c6d08729868e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/metrics/metric_registry.html">
<link rel="import" href="/tracing/value/histogram.html">

<script>
'use strict';

// The |androidStartupMetric| produces metrics that start counting at the
// earliest moment the Chrome code on Android is executed.
// A few histograms are produced with the names as described below:
//
// 1. messageloop_start_time - time till the message loop of the browser main
//    starts processing posted tasts (after having loaded the Profile)
// 2. experimental_content_start_time - time when the renderer enters the main
//    entrypoint.
// 3. experimental_navigation_start_time - This roughly corresponds to the time
//    the initial navigation network request is sent.
// 4. navigation_commit_time - This is when the renderer has received the first
//    part of the response from the network and started loading the page.
// 5. first_contentful_paint_time - time to the first contentful paint of the
//    page loaded at startup
//
// The metric also supports multiple browser restarts, in this case multiple
// samples would be added to the histograms above.
tr.exportTo('tr.metrics.sh', function() {
  const MESSAGE_LOOP_EVENT_NAME = 'Startup.BrowserMessageLoopStartTime';
  const CONTENT_START_EVENT_NAME = 'content::Start';
  const NAVIGATION_EVENT_NAME = 'Navigation StartToCommit';
  const FIRST_CONTENTFUL_PAINT_EVENT_NAME = 'firstContentfulPaint';
  function androidStartupMetric(histograms, model) {
    // Walk the browser slices, extract timestamps for the browser start,
    // message loop start.
    let messageLoopStartEvents = [];
    let navigationEvents = [];
    const chromeHelper =
        model.getOrCreateHelper(tr.model.helpers.ChromeModelHelper);
    if (!chromeHelper) return;
    for (const helper of chromeHelper.browserHelpers) {
      for (const ev of helper.mainThread.asyncSliceGroup.childEvents()) {
        if (ev.title === MESSAGE_LOOP_EVENT_NAME) {
          messageLoopStartEvents.push(ev);
        } else if (ev.title === NAVIGATION_EVENT_NAME) {
          navigationEvents.push(ev);
        }
      }
    }

    // Walk the renderer slices and extract the 'first contentful paint'
    // histogram samples.
    let contentStartEvents = [];
    let firstContentfulPaintEvents = [];
    const rendererHelpers = chromeHelper.rendererHelpers;
    const pids = Object.keys(rendererHelpers);
    for (const rendererHelper of Object.values(chromeHelper.rendererHelpers)) {
      if (!rendererHelper.mainThread) continue;
      for (const ev of rendererHelper.mainThread.sliceGroup.childEvents()) {
        if (ev.title === FIRST_CONTENTFUL_PAINT_EVENT_NAME) {
          firstContentfulPaintEvents.push(ev);
          // There are usually several 'First Contentful Paint' events recorded
          // for each page load. Take only the first one per renderer.
          break;
        } else if (ev.title === CONTENT_START_EVENT_NAME) {
          contentStartEvents.push(ev);
        }
      }
    }

    // Fallback to scanning all processes if important events are not found.
    let totalBrowserStarts = messageLoopStartEvents.length;
    let totalContentStartEvents = contentStartEvents.length;
    let totalFcpEvents = firstContentfulPaintEvents.length;
    let totalNavigations = navigationEvents.length;
    if (totalFcpEvents !== totalBrowserStarts ||
        totalNavigations !== totalBrowserStarts ||
        totalContentStartEvents !== totalBrowserStarts ||
        totalBrowserStarts === 0) {
      messageLoopStartEvents = [];
      contentStartEvents = [];
      navigationEvents = [];
      firstContentfulPaintEvents = [];
      // Sometimes either the browser process or the renderer process does not
      // have the proper name attached. This often happens when both chrome
      // trace and systrace are merged. Other multi-process trickery, like
      // Perfetto, may also cause this.
      for (const proc of Object.values(model.processes)) {
        for (const ev of proc.getDescendantEvents()) {
          if (ev.title === MESSAGE_LOOP_EVENT_NAME) {
            messageLoopStartEvents.push(ev);
          } else if (ev.title === NAVIGATION_EVENT_NAME) {
            navigationEvents.push(ev);
          } else if (ev.title === CONTENT_START_EVENT_NAME) {
            contentStartEvents.push(ev);
          }
        }
        for (const ev of proc.getDescendantEvents()) {
          if (ev.title === FIRST_CONTENTFUL_PAINT_EVENT_NAME) {
            firstContentfulPaintEvents.push(ev);
            break;
          }
        }
      }
      totalBrowserStarts = messageLoopStartEvents.length;
      totalContentStartEvents = contentStartEvents.length;
      totalNavigations = navigationEvents.length;
      totalFcpEvents = firstContentfulPaintEvents.length;
    }

    // Sometimes a number of early trace events are not recorded because tracing
    // takes time to start. This leads to having more FCP events than
    // messageloop_start events. As a workaround ignore the FCP events for which
    // there are no browser starts. Navigation and content start events are
    // recorded on a best effort basis if they are found in the trace; their
    // absence doesn't cause FCP events to be dropped.
    function orderEvents(event1, event2) {
      return event1.start - event2.start;
    }
    messageLoopStartEvents.sort(orderEvents);
    contentStartEvents.sort(orderEvents);
    navigationEvents.sort(orderEvents);
    firstContentfulPaintEvents.sort(orderEvents);

    if (totalFcpEvents < totalBrowserStarts) {
      throw new Error('Found fewer FCP events (' + totalFcpEvents +
          ') than browser starts (' + totalBrowserStarts + ')');
    }

    // Group the relevant events with the corresponding browser starts and emit
    // the metrics.
    const messageLoopStartHistogram = histograms.createHistogram(
        'messageloop_start_time',
        tr.b.Unit.byName.timeDurationInMs_smallerIsBetter, []);
    const contentStartHistogram = histograms.createHistogram(
        'experimental_content_start_time',
        tr.b.Unit.byName.timeDurationInMs_smallerIsBetter, []);
    const navigationStartHistogram = histograms.createHistogram(
        'experimental_navigation_start_time',
        tr.b.Unit.byName.timeDurationInMs_smallerIsBetter, []);
    const navigationCommitHistogram = histograms.createHistogram(
        'navigation_commit_time',
        tr.b.Unit.byName.timeDurationInMs_smallerIsBetter, []);
    const firstContentfulPaintHistogram = histograms.createHistogram(
        'first_contentful_paint_time',
        tr.b.Unit.byName.timeDurationInMs_smallerIsBetter, []);
    // The earliest browser start is skipped because it is affected by the state
    // of the system coming from the time before the benchmark started. Removing
    // these influencing factors allows reducing measurement noise.
    // Note: Two early starts are ignored below, the reasons for spurious
    // slowdowns of the 2nd run are not known yet, see http://crbug.com/891797.
    let contentIndex = 0;
    let navIndex = 0;
    let fcpIndex = 0;
    for (let loopStartIndex = 0; loopStartIndex < totalBrowserStarts;) {
      const startEvent = messageLoopStartEvents[loopStartIndex];
      if (fcpIndex === totalFcpEvents) {
        break;
      }

      // Skip all events that appear before the next browser start.
      const contentStartEvent = contentIndex < contentStartEvents.length ?
        contentStartEvents[contentIndex] : null;
      if (contentStartEvent && contentStartEvent.start < startEvent.start) {
        contentIndex++;
        continue;
      }
      const navEvent = navIndex < navigationEvents.length ?
        navigationEvents[navIndex] : null;
      if (navEvent && navEvent.start < startEvent.start) {
        navIndex++;
        continue;
      }
      const fcpEvent = firstContentfulPaintEvents[fcpIndex];
      if (fcpEvent.start < startEvent.start) {
        fcpIndex++;
        continue;
      }

      // The pair of matching events is found.
      loopStartIndex++;

      // Skip the two initial FCP events and (potentially missing) browser
      // starts.
      if (fcpIndex < 2) {
        continue;
      }

      // Record the histograms.
      messageLoopStartHistogram.addSample(startEvent.duration,
          {events: new tr.v.d.RelatedEventSet([startEvent])});
      if (contentStartEvent) {
        contentStartHistogram.addSample(
            contentStartEvent.start - startEvent.start,
            {events: new tr.v.d.RelatedEventSet([startEvent,
              contentStartEvent])});
      }
      if (navEvent) {
        navigationStartHistogram.addSample(
            navEvent.start - startEvent.start,
            {events: new tr.v.d.RelatedEventSet([startEvent, navEvent])});
        navigationCommitHistogram.addSample(
            navEvent.end - startEvent.start,
            {events: new tr.v.d.RelatedEventSet([startEvent, navEvent])});
      }
      firstContentfulPaintHistogram.addSample(
          fcpEvent.end - startEvent.start,
          {events: new tr.v.d.RelatedEventSet([startEvent, fcpEvent])});
    }
  }

  tr.metrics.MetricRegistry.register(androidStartupMetric);

  return {
    androidStartupMetric,
  };
});
</script>