timeline_summary.dart 21.5 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
import 'gc_summarizer.dart';
13 14
import 'percentile_utils.dart';
import 'profiling_summarizer.dart';
15
import 'raster_cache_summarizer.dart';
16
import 'refresh_rate_summarizer.dart';
17
import 'scene_display_lag_summarizer.dart';
18
import 'timeline.dart';
19
import 'vsync_frame_lag_summarizer.dart';
20

21
const JsonEncoder _prettyEncoder = JsonEncoder.withIndent('  ');
22 23 24

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

27 28 29 30 31 32
/// 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';

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

38
  final Timeline _timeline;
39 40 41

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

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

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

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

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

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

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

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

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

98 99 100
  /// The total number of rasterizer cycles recorded in the timeline.
  int countRasterizations() => _extractGpuRasterizerDrawDurations().length;

101 102 103 104 105 106 107 108 109 110 111 112 113 114
  /// 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;
  }

115
  /// Encodes this summary as JSON.
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
  ///
  /// 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.
166
  ///   See [SceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed].
167 168 169
  /// * "90th_percentile_vsync_transitions_missed" and
  ///   "99th_percentile_vsync_transitions_missed": The 90/99-th percentile
  ///   `vsync_transitions_missed` over the lag events.
170
  ///   See [SceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed].
171 172 173 174 175 176 177
  /// * "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].
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
  /// * "average_layer_cache_count": The average of the values seen for the
  ///   count of the engine layer cache entries.
  ///   See [RasterCacheSummarizer.computeAverageLayerCount].
  /// * "90th_percentile_layer_cache_count" and
  ///   "99th_percentile_layer_cache_count": The 90/99-th percentile values seen
  ///   for the count of the engine layer cache entries.
  ///   See [RasterCacheSummarizer.computePercentileLayerCount].
  /// * "worst_layer_cache_count": The worst (highest) value seen for the
  ///   count of the engine layer cache entries.
  ///   See [RasterCacheSummarizer.computeWorstLayerCount].
  /// * "average_layer_cache_memory": The average of the values seen for the
  ///   memory used for the engine layer cache entries, in megabytes.
  ///   See [RasterCacheSummarizer.computeAverageLayerMemory].
  /// * "90th_percentile_layer_cache_memory" and
  ///   "99th_percentile_layer_cache_memory": The 90/99-th percentile values seen
  ///   for the memory used for the engine layer cache entries.
  ///   See [RasterCacheSummarizer.computePercentileLayerMemory].
  /// * "worst_layer_cache_memory": The worst (highest) value seen for the
  ///   memory used for the engine layer cache entries.
  ///   See [RasterCacheSummarizer.computeWorstLayerMemory].
  /// * "average_picture_cache_count": The average of the values seen for the
  ///   count of the engine picture cache entries.
  ///   See [RasterCacheSummarizer.computeAveragePictureCount].
  /// * "90th_percentile_picture_cache_count" and
  ///   "99th_percentile_picture_cache_count": The 90/99-th percentile values seen
  ///   for the count of the engine picture cache entries.
  ///   See [RasterCacheSummarizer.computePercentilePictureCount].
  /// * "worst_picture_cache_count": The worst (highest) value seen for the
  ///   count of the engine picture cache entries.
  ///   See [RasterCacheSummarizer.computeWorstPictureCount].
  /// * "average_picture_cache_memory": The average of the values seen for the
  ///   memory used for the engine picture cache entries, in megabytes.
  ///   See [RasterCacheSummarizer.computeAveragePictureMemory].
  /// * "90th_percentile_picture_cache_memory" and
  ///   "99th_percentile_picture_cache_memory": The 90/99-th percentile values seen
  ///   for the memory used for the engine picture cache entries.
  ///   See [RasterCacheSummarizer.computePercentilePictureMemory].
  /// * "worst_picture_cache_memory": The worst (highest) value seen for the
  ///   memory used for the engine picture cache entries.
  ///   See [RasterCacheSummarizer.computeWorstPictureMemory].
218
  Map<String, dynamic> get summaryJson {
219
    final SceneDisplayLagSummarizer sceneDisplayLagSummarizer = _sceneDisplayLagSummarizer();
220
    final VsyncFrameLagSummarizer vsyncFrameLagSummarizer = _vsyncFrameLagSummarizer();
221
    final Map<String, dynamic> profilingSummary = _profilingSummarizer().summarize();
222
    final RasterCacheSummarizer rasterCacheSummarizer = _rasterCacheSummarizer();
223
    final GCSummarizer gcSummarizer = _gcSummarizer();
224
    final RefreshRateSummary refreshRateSummary = RefreshRateSummary(vsyncEvents: _extractNamedEvents(kUIThreadVsyncProcessEvent));
225

226
    final Map<String, dynamic> timelineSummary = <String, dynamic>{
227
      'average_frame_build_time_millis': computeAverageFrameBuildTimeMillis(),
228 229
      '90th_percentile_frame_build_time_millis': computePercentileFrameBuildTimeMillis(90.0),
      '99th_percentile_frame_build_time_millis': computePercentileFrameBuildTimeMillis(99.0),
230
      'worst_frame_build_time_millis': computeWorstFrameBuildTimeMillis(),
231
      'missed_frame_build_budget_count': computeMissedFrameBuildBudgetCount(),
232
      'average_frame_rasterizer_time_millis': computeAverageFrameRasterizerTimeMillis(),
233 234
      '90th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(90.0),
      '99th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(99.0),
235 236
      'worst_frame_rasterizer_time_millis': computeWorstFrameRasterizerTimeMillis(),
      'missed_frame_rasterizer_budget_count': computeMissedFrameRasterizerBudgetCount(),
237
      'frame_count': countFrames(),
238
      'frame_rasterizer_count': countRasterizations(),
239 240
      'new_gen_gc_count': newGenerationGarbageCollections(),
      'old_gen_gc_count': oldGenerationGarbageCollections(),
241
      'frame_build_times': _extractFrameDurations()
242 243
          .map<int>((Duration duration) => duration.inMicroseconds)
          .toList(),
244
      'frame_rasterizer_times': _extractGpuRasterizerDrawDurations()
245 246 247 248 249 250 251 252
          .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(),
253 254
      'average_vsync_transitions_missed': sceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed(),
      '90th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(90.0),
255
      '99th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(99.0),
256 257 258
      'average_vsync_frame_lag': vsyncFrameLagSummarizer.computeAverageVsyncFrameLag(),
      '90th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(90.0),
      '99th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(99.0),
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
      'average_layer_cache_count': rasterCacheSummarizer.computeAverageLayerCount(),
      '90th_percentile_layer_cache_count': rasterCacheSummarizer.computePercentileLayerCount(90.0),
      '99th_percentile_layer_cache_count': rasterCacheSummarizer.computePercentileLayerCount(99.0),
      'worst_layer_cache_count': rasterCacheSummarizer.computeWorstLayerCount(),
      'average_layer_cache_memory': rasterCacheSummarizer.computeAverageLayerMemory(),
      '90th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(90.0),
      '99th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(99.0),
      'worst_layer_cache_memory': rasterCacheSummarizer.computeWorstLayerMemory(),
      'average_picture_cache_count': rasterCacheSummarizer.computeAveragePictureCount(),
      '90th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(90.0),
      '99th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(99.0),
      'worst_picture_cache_count': rasterCacheSummarizer.computeWorstPictureCount(),
      'average_picture_cache_memory': rasterCacheSummarizer.computeAveragePictureMemory(),
      '90th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(90.0),
      '99th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(99.0),
      'worst_picture_cache_memory': rasterCacheSummarizer.computeWorstPictureMemory(),
275
      'total_ui_gc_time': gcSummarizer.totalGCTimeMillis,
276 277 278 279 280
      '30hz_frame_percentage': refreshRateSummary.percentageOf30HzFrames,
      '60hz_frame_percentage': refreshRateSummary.percentageOf60HzFrames,
      '90hz_frame_percentage': refreshRateSummary.percentageOf90HzFrames,
      '120hz_frame_percentage': refreshRateSummary.percentageOf120HzFrames,
      'illegal_refresh_rate_frame_count': refreshRateSummary.framesWithIllegalRefreshRate.length,
281
    };
282 283 284

    timelineSummary.addAll(profilingSummary);
    return timelineSummary;
285 286 287
  }

  /// Writes all of the recorded timeline data to a file.
288
  ///
289 290 291 292
  /// 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.
  ///
293 294 295
  /// See also:
  ///
  /// * [Timeline.fromJson], which explains detail about the timeline data.
296
  Future<void> writeTimelineToFile(
297
    String traceName, {
298
    String? destinationDirectory,
299
    bool pretty = false,
300
    bool includeSummary = true,
301
  }) async {
302
    destinationDirectory ??= testOutputsDirectory;
303
    await fs.directory(destinationDirectory).create(recursive: true);
304
    final File file = fs.file(path.join(destinationDirectory, '$traceName.timeline.json'));
305
    await file.writeAsString(_encodeJson(_timeline.json, pretty));
306 307 308 309

    if (includeSummary) {
      await _writeSummaryToFile(traceName, destinationDirectory: destinationDirectory, pretty: pretty);
    }
310 311 312
  }

  /// Writes [summaryJson] to a file.
313 314 315 316
  @Deprecated(
    'Use TimelineSummary.writeTimelineToFile. '
    'This feature was deprecated after v2.1.0-13.0.pre.'
  )
317
  Future<void> writeSummaryToFile(
318
    String traceName, {
319
    String? destinationDirectory,
320
    bool pretty = false,
321
  }) async {
322
    destinationDirectory ??= testOutputsDirectory;
323 324 325 326 327 328 329 330
    await _writeSummaryToFile(traceName, destinationDirectory: destinationDirectory, pretty: pretty);
  }

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

336
  String _encodeJson(Map<String, dynamic> jsonObject, bool pretty) {
337
    return pretty
338 339
      ? _prettyEncoder.convert(jsonObject)
      : json.encode(jsonObject);
340 341
  }

342
  List<TimelineEvent> _extractNamedEvents(String name) {
343
    return _timeline.events!
344
      .where((TimelineEvent event) => event.name == name)
345 346 347
      .toList();
  }

348
  List<TimelineEvent> _extractEventsWithNames(Set<String> names) {
349
    return _timeline.events!
350
      .where((TimelineEvent event) => names.contains(event.name))
351 352 353
      .toList();
  }

354 355
  List<Duration> _extractDurations(
    String name,
356
    Duration Function(TimelineEvent beginEvent, TimelineEvent endEvent) extractor,
357
  ) {
358
    final List<Duration> result = <Duration>[];
359
    final List<TimelineEvent> events = _extractNamedEvents(name);
360 361

    // Timeline does not guarantee that the first event is the "begin" event.
362
    TimelineEvent? begin;
363
    for (final TimelineEvent event in events) {
364
      if (event.phase == 'B' || event.phase == 'b') {
365 366 367 368 369 370 371
        begin = event;
      } else {
        if (begin != null) {
          result.add(extractor(begin, event));
          // each begin only gets used once.
          begin = null;
        }
372 373 374 375 376 377
      }
    }

    return result;
  }

378 379
  /// Extracts Duration list that are reported as a pair of begin/end events.
  ///
380 381 382 383 384 385
  /// 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].
386 387 388 389 390
  /// See: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
  List<Duration> _extractBeginEndEvents(String name) {
    return _extractDurations(
      name,
      (TimelineEvent beginEvent, TimelineEvent endEvent) {
391
        return Duration(microseconds: endEvent.timestampMicros! - beginEvent.timestampMicros!);
392 393 394 395 396 397 398 399
      },
    );
  }

  List<Duration> _extractBeginTimestamps(String name) {
    final List<Duration> result = _extractDurations(
      name,
      (TimelineEvent beginEvent, TimelineEvent endEvent) {
400
        return Duration(microseconds: beginEvent.timestampMicros!);
401 402 403 404 405 406 407 408 409 410
      },
    );

    // 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;
  }

411 412
  double _averageInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
413
      throw ArgumentError('durations is empty!');
414
    final double total = durations.fold<double>(0.0, (double t, Duration duration) => t + duration.inMicroseconds.toDouble() / 1000.0);
415
    return total / durations.length;
416 417
  }

418 419
  double _percentileInMillis(Iterable<Duration> durations, double percentile) {
    if (durations.isEmpty)
420
      throw ArgumentError('durations is empty!');
421
    assert(percentile >= 0.0 && percentile <= 100.0);
422
    final List<double> doubles = durations.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0).toList();
423
    return findPercentile(doubles, percentile);
424 425
  }

426 427
  double _maxInMillis(Iterable<Duration> durations) {
    if (durations.isEmpty)
428
      throw ArgumentError('durations is empty!');
429
    return durations
430
        .map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0)
431
        .reduce(math.max);
432 433
  }

434 435
  SceneDisplayLagSummarizer _sceneDisplayLagSummarizer() => SceneDisplayLagSummarizer(_extractNamedEvents(kSceneDisplayLagEvent));

436
  List<Duration> _extractGpuRasterizerDrawDurations() => _extractBeginEndEvents(kRasterizeFrameEventName);
437

438
  ProfilingSummarizer _profilingSummarizer() => ProfilingSummarizer.fromEvents(_extractEventsWithNames(kProfilingEvents));
439

440
  List<Duration> _extractFrameDurations() => _extractBeginEndEvents(kBuildFrameEventName);
441 442

  VsyncFrameLagSummarizer _vsyncFrameLagSummarizer() => VsyncFrameLagSummarizer(_extractEventsWithNames(kVsyncTimelineEventNames));
443 444

  RasterCacheSummarizer _rasterCacheSummarizer() => RasterCacheSummarizer(_extractNamedEvents(kRasterCacheEvent));
445 446

  GCSummarizer _gcSummarizer() => GCSummarizer.fromEvents(_extractEventsWithNames(kGCRootEvents));
447
}