timeline_summary.dart 16.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

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

import 'common.dart';
12 13
import 'percentile_utils.dart';
import 'profiling_summarizer.dart';
14
import 'scene_display_lag_summarizer.dart';
15
import 'timeline.dart';
16
import 'vsync_frame_lag_summarizer.dart';
17

18
const JsonEncoder _prettyEncoder = JsonEncoder.withIndent('  ');
19 20 21

/// 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.
22
const Duration kBuildBudget = Duration(milliseconds: 16);
23

24 25 26 27 28 29
/// The name of the framework frame build events we need to filter or extract.
const String kBuildFrameEventName = 'Frame';

/// The name of the engine frame rasterization events we need to filter or extract.
const String kRasterizeFrameEventName = 'GPURasterizer::Draw';

30
/// Extracts statistics from a [Timeline].
31
class TimelineSummary {
32
  /// Creates a timeline summary given a full timeline object.
33
  TimelineSummary.summarize(this._timeline);
34

35
  final Timeline _timeline;
36 37 38

  /// Average amount of time spent per frame in the framework building widgets,
  /// updating layout, painting and compositing.
39
  ///
40
  /// Returns null if no frames were recorded.
41
  double computeAverageFrameBuildTimeMillis() {
42
    return _averageInMillis(_extractFrameDurations());
43 44
  }

45 46 47 48 49 50 51
  /// The [p]-th percentile frame rasterization time in milliseconds.
  ///
  /// Returns null if no frames were recorded.
  double computePercentileFrameBuildTimeMillis(double p) {
    return _percentileInMillis(_extractFrameDurations(), p);
  }

52
  /// The longest frame build time in milliseconds.
53
  ///
54
  /// Returns null if no frames were recorded.
55
  double computeWorstFrameBuildTimeMillis() {
56
    return _maxInMillis(_extractFrameDurations());
57 58
  }

59
  /// The number of frames that missed the [kBuildBudget] and therefore are
60
  /// in the danger of missing frames.
61
  int computeMissedFrameBuildBudgetCount([ Duration frameBuildBudget = kBuildBudget ]) => _extractFrameDurations()
62
    .where((Duration duration) => duration > kBuildBudget)
63 64
    .length;

65
  /// Average amount of time spent per frame in the engine rasterizer.
66
  ///
67
  /// Returns null if no frames were recorded.
68
  double computeAverageFrameRasterizerTimeMillis() {
69
    return _averageInMillis(_extractGpuRasterizerDrawDurations());
70 71 72 73
  }

  /// The longest frame rasterization time in milliseconds.
  ///
74
  /// Returns null if no frames were recorded.
75
  double computeWorstFrameRasterizerTimeMillis() {
76
    return _maxInMillis(_extractGpuRasterizerDrawDurations());
77 78
  }

79 80 81 82
  /// The [p]-th percentile frame rasterization time in milliseconds.
  ///
  /// Returns null if no frames were recorded.
  double computePercentileFrameRasterizerTimeMillis(double p) {
83
    return _percentileInMillis(_extractGpuRasterizerDrawDurations(), p);
84 85
  }

86 87
  /// The number of frames that missed the [kBuildBudget] on the raster thread
  /// and therefore are in the danger of missing frames.
88 89
  int computeMissedFrameRasterizerBudgetCount([ Duration frameBuildBudget = kBuildBudget ]) => _extractGpuRasterizerDrawDurations()
      .where((Duration duration) => duration > kBuildBudget)
90 91 92
      .length;

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

95 96 97
  /// The total number of rasterizer cycles recorded in the timeline.
  int countRasterizations() => _extractGpuRasterizerDrawDurations().length;

98 99 100 101 102 103 104 105 106 107 108 109 110 111
  /// The total number of old generation garbage collections recorded in the timeline.
  int oldGenerationGarbageCollections() {
    return _timeline.events!.where((TimelineEvent event) {
      return event.category == 'GC' && event.name == 'CollectOldGeneration';
    }).length;
  }

  /// The total number of new generation garbage collections recorded in the timeline.
  int newGenerationGarbageCollections() {
    return _timeline.events!.where((TimelineEvent event) {
      return event.category == 'GC' && event.name == 'CollectNewGeneration';
    }).length;
  }

112
  /// Encodes this summary as JSON.
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
  ///
  /// Data ends with "_time_millis" means time in milliseconds and numbers in
  /// the "frame_build_times", "frame_rasterizer_times", "frame_begin_times" and
  /// "frame_rasterizer_begin_times" lists are in microseconds.
  ///
  /// * "average_frame_build_time_millis": Average amount of time spent per
  ///   frame in the framework building widgets, updating layout, painting and
  ///   compositing.
  ///   See [computeAverageFrameBuildTimeMillis].
  /// * "90th_percentile_frame_build_time_millis" and
  ///   "99th_percentile_frame_build_time_millis": The p-th percentile frame
  ///   rasterization time in milliseconds. 90 and 99-th percentile number is
  ///   usually a better metric to estimate worse cases. See discussion in
  ///   https://github.com/flutter/flutter/pull/19121#issuecomment-419520765
  ///   See [computePercentileFrameBuildTimeMillis].
  /// * "worst_frame_build_time_millis": The longest frame build time.
  ///   See [computeWorstFrameBuildTimeMillis].
  /// * "missed_frame_build_budget_count': The number of frames that missed
  ///   the [kBuildBudget] and therefore are in the danger of missing frames.
  ///   See [computeMissedFrameBuildBudgetCount].
  /// * "average_frame_rasterizer_time_millis": Average amount of time spent
  ///   per frame in the engine rasterizer.
  ///   See [computeAverageFrameRasterizerTimeMillis].
  /// * "90th_percentile_frame_rasterizer_time_millis" and
  ///   "99th_percentile_frame_rasterizer_time_millis": The 90/99-th percentile
  ///   frame rasterization time in milliseconds.
  ///   See [computePercentileFrameRasterizerTimeMillis].
  /// * "worst_frame_rasterizer_time_millis": The longest frame rasterization
  ///   time.
  ///   See [computeWorstFrameRasterizerTimeMillis].
  /// * "missed_frame_rasterizer_budget_count": The number of frames that missed
  ///   the [kBuildBudget] on the raster thread and therefore are in the danger
  ///   of missing frames.
  ///   See [computeMissedFrameRasterizerBudgetCount].
  /// * "frame_count": The total number of frames recorded in the timeline. This
  ///   is also the length of the "frame_build_times" and the "frame_begin_times"
  ///   lists.
  ///   See [countFrames].
  /// * "frame_rasterizer_count": The total number of rasterizer cycles recorded
  ///   in the timeline. This is also the length of the "frame_rasterizer_times"
  ///   and the "frame_rasterizer_begin_times" lists.
  ///   See [countRasterizations].
  /// * "frame_build_times": The build time of each frame, by tracking the
  ///   [TimelineEvent] with name [kBuildFrameEventName].
  /// * "frame_rasterizer_times": The rasterize time of each frame, by tracking
  ///   the [TimelineEvent] with name [kRasterizeFrameEventName]
  /// * "frame_begin_times": The build begin timestamp of each frame.
  /// * "frame_rasterizer_begin_times": The rasterize begin time of each frame.
  /// * "average_vsync_transitions_missed": Computes the average of the
  ///   `vsync_transitions_missed` over the lag events.
163
  ///   See [SceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed].
164 165 166
  /// * "90th_percentile_vsync_transitions_missed" and
  ///   "99th_percentile_vsync_transitions_missed": The 90/99-th percentile
  ///   `vsync_transitions_missed` over the lag events.
167
  ///   See [SceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed].
168 169 170 171 172 173 174
  /// * "average_vsync_frame_lag": Computes the average of the time between
  ///   platform vsync signal and the engine frame process start time.
  ///   See [VsyncFrameLagSummarizer.computeAverageVsyncFrameLag].
  /// * "90th_percentile_vsync_frame_lag" and "99th_percentile_vsync_frame_lag":
  ///   The 90/99-th percentile delay between platform vsync signal and engine
  ///   frame process start time.
  ///   See [VsyncFrameLagSummarizer.computePercentileVsyncFrameLag].
175
  Map<String, dynamic> get summaryJson {
176
    final SceneDisplayLagSummarizer sceneDisplayLagSummarizer = _sceneDisplayLagSummarizer();
177
    final VsyncFrameLagSummarizer vsyncFrameLagSummarizer = _vsyncFrameLagSummarizer();
178
    final Map<String, dynamic> profilingSummary = _profilingSummarizer().summarize();
179

180
    final Map<String, dynamic> timelineSummary = <String, dynamic>{
181
      'average_frame_build_time_millis': computeAverageFrameBuildTimeMillis(),
182 183
      '90th_percentile_frame_build_time_millis': computePercentileFrameBuildTimeMillis(90.0),
      '99th_percentile_frame_build_time_millis': computePercentileFrameBuildTimeMillis(99.0),
184
      'worst_frame_build_time_millis': computeWorstFrameBuildTimeMillis(),
185
      'missed_frame_build_budget_count': computeMissedFrameBuildBudgetCount(),
186
      'average_frame_rasterizer_time_millis': computeAverageFrameRasterizerTimeMillis(),
187 188
      '90th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(90.0),
      '99th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(99.0),
189 190
      'worst_frame_rasterizer_time_millis': computeWorstFrameRasterizerTimeMillis(),
      'missed_frame_rasterizer_budget_count': computeMissedFrameRasterizerBudgetCount(),
191
      'frame_count': countFrames(),
192
      'frame_rasterizer_count': countRasterizations(),
193 194
      'new_gen_gc_count': newGenerationGarbageCollections(),
      'old_gen_gc_count': oldGenerationGarbageCollections(),
195
      'frame_build_times': _extractFrameDurations()
196 197
          .map<int>((Duration duration) => duration.inMicroseconds)
          .toList(),
198
      'frame_rasterizer_times': _extractGpuRasterizerDrawDurations()
199 200 201 202 203 204 205 206
          .map<int>((Duration duration) => duration.inMicroseconds)
          .toList(),
      'frame_begin_times': _extractBeginTimestamps(kBuildFrameEventName)
          .map<int>((Duration duration) => duration.inMicroseconds)
          .toList(),
      'frame_rasterizer_begin_times': _extractBeginTimestamps(kRasterizeFrameEventName)
          .map<int>((Duration duration) => duration.inMicroseconds)
          .toList(),
207 208
      'average_vsync_transitions_missed': sceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed(),
      '90th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(90.0),
209
      '99th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(99.0),
210 211 212
      'average_vsync_frame_lag': vsyncFrameLagSummarizer.computeAverageVsyncFrameLag(),
      '90th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(90.0),
      '99th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(99.0),
213
    };
214 215 216

    timelineSummary.addAll(profilingSummary);
    return timelineSummary;
217 218 219
  }

  /// Writes all of the recorded timeline data to a file.
220
  ///
221 222 223 224
  /// By default, this will dump [summaryJson] to a companion file named
  /// `$traceName.timeline_summary.json`. If you want to skip the summary, set
  /// the `includeSummary` parameter to false.
  ///
225 226 227
  /// See also:
  ///
  /// * [Timeline.fromJson], which explains detail about the timeline data.
228
  Future<void> writeTimelineToFile(
229
    String traceName, {
230
    String? destinationDirectory,
231
    bool pretty = false,
232
    bool includeSummary = true,
233
  }) async {
234
    destinationDirectory ??= testOutputsDirectory;
235
    await fs.directory(destinationDirectory).create(recursive: true);
236
    final File file = fs.file(path.join(destinationDirectory, '$traceName.timeline.json'));
237
    await file.writeAsString(_encodeJson(_timeline.json, pretty));
238 239 240 241

    if (includeSummary) {
      await _writeSummaryToFile(traceName, destinationDirectory: destinationDirectory, pretty: pretty);
    }
242 243 244
  }

  /// Writes [summaryJson] to a file.
245 246 247 248
  @Deprecated(
    'Use TimelineSummary.writeTimelineToFile. '
    'This feature was deprecated after v2.1.0-13.0.pre.'
  )
249
  Future<void> writeSummaryToFile(
250
    String traceName, {
251
    String? destinationDirectory,
252
    bool pretty = false,
253
  }) async {
254
    destinationDirectory ??= testOutputsDirectory;
255 256 257 258 259 260 261 262
    await _writeSummaryToFile(traceName, destinationDirectory: destinationDirectory, pretty: pretty);
  }

  Future<void> _writeSummaryToFile(
    String traceName, {
    required String destinationDirectory,
    bool pretty = false,
  }) async {
263
    await fs.directory(destinationDirectory).create(recursive: true);
264
    final File file = fs.file(path.join(destinationDirectory, '$traceName.timeline_summary.json'));
265 266 267
    await file.writeAsString(_encodeJson(summaryJson, pretty));
  }

268
  String _encodeJson(Map<String, dynamic> jsonObject, bool pretty) {
269
    return pretty
270 271
      ? _prettyEncoder.convert(jsonObject)
      : json.encode(jsonObject);
272 273
  }

274
  List<TimelineEvent> _extractNamedEvents(String name) {
275
    return _timeline.events!
276
      .where((TimelineEvent event) => event.name == name)
277 278 279
      .toList();
  }

280
  List<TimelineEvent> _extractEventsWithNames(Set<String> names) {
281
    return _timeline.events!
282
      .where((TimelineEvent event) => names.contains(event.name))
283 284 285
      .toList();
  }

286 287
  List<Duration> _extractDurations(
    String name,
288
    Duration Function(TimelineEvent beginEvent, TimelineEvent endEvent) extractor,
289
  ) {
290
    final List<Duration> result = <Duration>[];
291
    final List<TimelineEvent> events = _extractNamedEvents(name);
292 293

    // Timeline does not guarantee that the first event is the "begin" event.
294
    TimelineEvent? begin;
295 296 297 298 299 300 301 302 303
    for (final TimelineEvent event in events) {
      if (event.phase == 'B') {
        begin = event;
      } else {
        if (begin != null) {
          result.add(extractor(begin, event));
          // each begin only gets used once.
          begin = null;
        }
304 305 306 307 308 309
      }
    }

    return result;
  }

310 311
  /// Extracts Duration list that are reported as a pair of begin/end events.
  ///
312 313 314 315 316 317
  /// Extracts Duration of events by looking for events with the name and phase
  /// begin ("ph": "B"). This routine assumes that the next event with the same
  /// name is phase end ("ph": "E"), but it's not examined.
  /// "SceneDisplayLag" event is an exception, with phase ("ph") labeled
  /// 'b' and 'e', meaning begin and end phase for an async event.
  /// See [SceneDisplayLagSummarizer].
318 319 320 321 322
  /// See: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
  List<Duration> _extractBeginEndEvents(String name) {
    return _extractDurations(
      name,
      (TimelineEvent beginEvent, TimelineEvent endEvent) {
323
        return Duration(microseconds: endEvent.timestampMicros! - beginEvent.timestampMicros!);
324 325 326 327 328 329 330 331
      },
    );
  }

  List<Duration> _extractBeginTimestamps(String name) {
    final List<Duration> result = _extractDurations(
      name,
      (TimelineEvent beginEvent, TimelineEvent endEvent) {
332
        return Duration(microseconds: beginEvent.timestampMicros!);
333 334 335 336 337 338 339 340 341 342
      },
    );

    // Align timestamps so the first event is at 0.
    for (int i = result.length - 1; i >= 0; i -= 1) {
      result[i] = result[i] - result[0];
    }
    return result;
  }

343 344
  double _averageInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
345
      throw ArgumentError('durations is empty!');
346
    final double total = durations.fold<double>(0.0, (double t, Duration duration) => t + duration.inMicroseconds.toDouble() / 1000.0);
347
    return total / durations.length;
348 349
  }

350 351
  double _percentileInMillis(Iterable<Duration> durations, double percentile) {
    if (durations.isEmpty)
352
      throw ArgumentError('durations is empty!');
353
    assert(percentile >= 0.0 && percentile <= 100.0);
354
    final List<double> doubles = durations.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0).toList();
355
    return findPercentile(doubles, percentile);
356 357
  }

358 359
  double _maxInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
360
      throw ArgumentError('durations is empty!');
361
    return durations
362
        .map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0)
363
        .reduce(math.max);
364 365
  }

366 367
  SceneDisplayLagSummarizer _sceneDisplayLagSummarizer() => SceneDisplayLagSummarizer(_extractNamedEvents(kSceneDisplayLagEvent));

368
  List<Duration> _extractGpuRasterizerDrawDurations() => _extractBeginEndEvents(kRasterizeFrameEventName);
369

370
  ProfilingSummarizer _profilingSummarizer() => ProfilingSummarizer.fromEvents(_extractEventsWithNames(kProfilingEvents));
371

372
  List<Duration> _extractFrameDurations() => _extractBeginEndEvents(kBuildFrameEventName);
373 374

  VsyncFrameLagSummarizer _vsyncFrameLagSummarizer() => VsyncFrameLagSummarizer(_extractEventsWithNames(kVsyncTimelineEventNames));
375
}