timeline_summary.dart 7.92 KB
Newer Older
1 2 3 4 5
// Copyright 2016 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.

import 'dart:async';
6
import 'dart:convert' show json, JsonEncoder;
7
import 'dart:math' as math;
8 9 10 11 12

import 'package:file/file.dart';
import 'package:path/path.dart' as path;

import 'common.dart';
13
import 'timeline.dart';
14

15
const JsonEncoder _prettyEncoder = JsonEncoder.withIndent('  ');
16 17 18

/// The maximum amount of time considered safe to spend for a frame's build
/// phase. Anything past that is in the danger of missing the frame as 60FPS.
19
const Duration kBuildBudget = Duration(milliseconds: 8);
20

21
/// Extracts statistics from a [Timeline].
22
class TimelineSummary {
23
  /// Creates a timeline summary given a full timeline object.
24
  TimelineSummary.summarize(this._timeline);
25

26
  final Timeline _timeline;
27 28 29

  /// Average amount of time spent per frame in the framework building widgets,
  /// updating layout, painting and compositing.
30
  ///
31
  /// Returns null if no frames were recorded.
32
  double computeAverageFrameBuildTimeMillis() {
33
    return _averageInMillis(_extractFrameDurations());
34 35
  }

36
  /// The longest frame build time in milliseconds.
37
  ///
38
  /// Returns null if no frames were recorded.
39
  double computeWorstFrameBuildTimeMillis() {
40
    return _maxInMillis(_extractFrameDurations());
41 42
  }

43
  /// The number of frames that missed the [kBuildBudget] and therefore are
44
  /// in the danger of missing frames.
45
  int computeMissedFrameBuildBudgetCount([Duration frameBuildBudget = kBuildBudget]) => _extractFrameDurations()
46
    .where((Duration duration) => duration > kBuildBudget)
47 48
    .length;

49 50
  /// Average amount of time spent per frame in the GPU rasterizer.
  ///
51
  /// Returns null if no frames were recorded.
52
  double computeAverageFrameRasterizerTimeMillis() {
53
    return _averageInMillis(_extractDuration(_extractGpuRasterizerDrawEvents()));
54 55 56 57
  }

  /// The longest frame rasterization time in milliseconds.
  ///
58
  /// Returns null if no frames were recorded.
59
  double computeWorstFrameRasterizerTimeMillis() {
60
    return _maxInMillis(_extractDuration(_extractGpuRasterizerDrawEvents()));
61 62
  }

63 64 65 66 67 68 69
  /// The [p]-th percentile frame rasterization time in milliseconds.
  ///
  /// Returns null if no frames were recorded.
  double computePercentileFrameRasterizerTimeMillis(double p) {
    return _percentileInMillis(_extractDuration(_extractGpuRasterizerDrawEvents()), p);
  }

70 71 72 73 74 75 76
  /// The number of frames that missed the [kBuildBudget] on the GPU and
  /// therefore are in the danger of missing frames.
  int computeMissedFrameRasterizerBudgetCount([Duration frameBuildBudget = kBuildBudget]) => _extractGpuRasterizerDrawEvents()
      .where((TimedEvent event) => event.duration > kBuildBudget)
      .length;

  /// The total number of frames recorded in the timeline.
77
  int countFrames() => _extractFrameDurations().length;
78

79 80 81 82
  /// Encodes this summary as JSON.
  Map<String, dynamic> get summaryJson {
    return <String, dynamic> {
      'average_frame_build_time_millis': computeAverageFrameBuildTimeMillis(),
83
      'worst_frame_build_time_millis': computeWorstFrameBuildTimeMillis(),
84
      'missed_frame_build_budget_count': computeMissedFrameBuildBudgetCount(),
85
      'average_frame_rasterizer_time_millis': computeAverageFrameRasterizerTimeMillis(),
86 87
      '90th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(90.0),
      '99th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(99.0),
88 89
      'worst_frame_rasterizer_time_millis': computeWorstFrameRasterizerTimeMillis(),
      'missed_frame_rasterizer_budget_count': computeMissedFrameRasterizerBudgetCount(),
90
      'frame_count': countFrames(),
91
      'frame_build_times': _extractFrameDurations()
92
        .map((Duration duration) => duration.inMicroseconds)
93 94 95 96
        .toList(),
      'frame_rasterizer_times': _extractGpuRasterizerDrawEvents()
          .map((TimedEvent event) => event.duration.inMicroseconds)
          .toList(),
97 98 99 100
    };
  }

  /// Writes all of the recorded timeline data to a file.
101 102 103
  Future<Null> writeTimelineToFile(
    String traceName, {
    String destinationDirectory,
104
    bool pretty = false,
105
  }) async {
106
    destinationDirectory ??= testOutputsDirectory;
107
    await fs.directory(destinationDirectory).create(recursive: true);
108
    final File file = fs.file(path.join(destinationDirectory, '$traceName.timeline.json'));
109
    await file.writeAsString(_encodeJson(_timeline.json, pretty));
110 111 112
  }

  /// Writes [summaryJson] to a file.
113 114 115
  Future<Null> writeSummaryToFile(
    String traceName, {
    String destinationDirectory,
116
    bool pretty = false,
117
  }) async {
118
    destinationDirectory ??= testOutputsDirectory;
119
    await fs.directory(destinationDirectory).create(recursive: true);
120
    final File file = fs.file(path.join(destinationDirectory, '$traceName.timeline_summary.json'));
121 122 123
    await file.writeAsString(_encodeJson(summaryJson, pretty));
  }

124
  String _encodeJson(Map<String, dynamic> jsonObject, bool pretty) {
125
    return pretty
126 127
      ? _prettyEncoder.convert(jsonObject)
      : json.encode(jsonObject);
128 129
  }

130 131 132
  List<TimelineEvent> _extractNamedEvents(String name) {
    return _timeline.events
      .where((TimelineEvent event) => event.name == name)
133 134 135
      .toList();
  }

136 137
  List<Duration> _extractDurations(String name) {
    return _extractNamedEvents(name).map((TimelineEvent event) => event.duration).toList();
138 139
  }

140 141 142 143
  /// Extracts timed events that are reported as a pair of begin/end events.
  ///
  /// See: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
  List<TimedEvent> _extractBeginEndEvents(String name) {
144
    final List<TimedEvent> result = <TimedEvent>[];
145 146

    // Timeline does not guarantee that the first event is the "begin" event.
147
    final Iterator<TimelineEvent> events = _extractNamedEvents(name)
148
        .skipWhile((TimelineEvent evt) => evt.phase != 'B').iterator;
149
    while (events.moveNext()) {
150
      final TimelineEvent beginEvent = events.current;
151
      if (events.moveNext()) {
152
        final TimelineEvent endEvent = events.current;
153 154 155 156 157 158 159 160 161 162
        result.add(new TimedEvent(
            beginEvent.timestampMicros,
            endEvent.timestampMicros
        ));
      }
    }

    return result;
  }

163 164
  double _averageInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
165
      throw new ArgumentError('durations is empty!');
166

167
    final int total = durations.fold<int>(0, (int t, Duration duration) => t + duration.inMilliseconds);
168
    return total / durations.length;
169 170
  }

171 172
  double _percentileInMillis(Iterable<Duration> durations, double percentile) {
    if (durations.isEmpty)
173
      throw new ArgumentError('durations is empty!');
174 175 176 177 178 179 180 181

    assert(percentile >= 0.0 && percentile <= 100.0);
    final List<double> doubles = durations.map<double>((Duration duration) => duration.inMilliseconds.toDouble()).toList();
    doubles.sort();
    return doubles[((doubles.length - 1) * (percentile / 100)).round()];

  }

182 183
  double _maxInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
184
      throw new ArgumentError('durations is empty!');
185

186 187
    return durations
        .map<double>((Duration duration) => duration.inMilliseconds.toDouble())
188
        .reduce(math.max);
189 190 191
  }

  List<TimedEvent> _extractGpuRasterizerDrawEvents() => _extractBeginEndEvents('GPURasterizer::Draw');
192

193
  List<Duration> _extractFrameDurations() => _extractDurations('Frame');
194 195 196 197

  Iterable<Duration> _extractDuration(Iterable<TimedEvent> events) {
    return events.map((TimedEvent e) => e.duration);
  }
198 199 200 201
}

/// Timing information about an event that happened in the event loop.
class TimedEvent {
202 203 204 205
  /// Creates a timed event given begin and end timestamps in microseconds.
  TimedEvent(this.beginTimeMicros, this.endTimeMicros)
    : this.duration = new Duration(microseconds: endTimeMicros - beginTimeMicros);

206 207 208 209 210 211 212 213 214
  /// The timestamp when the event began.
  final int beginTimeMicros;

  /// The timestamp when the event ended.
  final int endTimeMicros;

  /// The duration of the event.
  final Duration duration;
}