perf_tests.dart 69.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// 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 LineSplitter, json, utf8;
7
import 'dart:io';
8
import 'dart:math' as math;
9

10 11
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
12
import 'package:xml/xml.dart';
13

14 15 16 17 18
import '../framework/devices.dart';
import '../framework/framework.dart';
import '../framework/host_agent.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
19

20 21 22
/// Must match flutter_driver/lib/src/common.dart.
///
/// Redefined here to avoid taking a dependency on flutter_driver.
Dan Field's avatar
Dan Field committed
23 24 25
String _testOutputDirectory(String testDirectory) {
  return Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? '$testDirectory/build';
}
26

27 28 29
TaskFunction createComplexLayoutScrollPerfTest({
  bool measureCpuGpu = true,
  bool badScroll = false,
30
  bool? enableImpeller,
31
}) {
32
  return PerfTest(
33
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
34 35 36
    badScroll
      ? 'test_driver/scroll_perf_bad.dart'
      : 'test_driver/scroll_perf.dart',
37
    'complex_layout_scroll_perf',
38
    measureCpuGpu: measureCpuGpu,
39
    enableImpeller: enableImpeller,
40
  ).run;
41 42
}

43
TaskFunction createTilesScrollPerfTest({bool? enableImpeller}) {
44
  return PerfTest(
45 46 47
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
    'test_driver/scroll_perf.dart',
    'tiles_scroll_perf',
48
    enableImpeller: enableImpeller,
49 50 51
  ).run;
}

52
TaskFunction createUiKitViewScrollPerfTest({bool? enableImpeller}) {
53 54
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
55 56 57
    'test_driver/uikit_view_scroll_perf.dart',
    'platform_views_scroll_perf',
    testDriver: 'test_driver/scroll_perf_test.dart',
58
    needsFullTimeline: false,
59
    enableImpeller: enableImpeller,
60 61 62
  ).run;
}

63
TaskFunction createUiKitViewScrollPerfNonIntersectingTest({bool? enableImpeller}) {
64 65 66 67 68 69 70 71 72 73
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
    'test_driver/uikit_view_scroll_perf_non_intersecting.dart',
    'platform_views_scroll_perf_non_intersecting',
    testDriver: 'test_driver/scroll_perf_non_intersecting_test.dart',
    needsFullTimeline: false,
    enableImpeller: enableImpeller,
  ).run;
}

74
TaskFunction createAndroidTextureScrollPerfTest({bool? enableImpeller}) {
75 76
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout',
77
    'test_driver/android_view_scroll_perf.dart',
78
    'platform_views_scroll_perf',
79
    testDriver: 'test_driver/scroll_perf_test.dart',
80 81
    needsFullTimeline: false,
    enableImpeller: enableImpeller,
82 83 84 85 86
  ).run;
}

TaskFunction createAndroidViewScrollPerfTest() {
  return PerfTest(
87
    '${flutterDirectory.path}/dev/benchmarks/platform_views_layout_hybrid_composition',
88
    'test_driver/android_view_scroll_perf.dart',
89
    'platform_views_scroll_perf_hybrid_composition',
90
    testDriver: 'test_driver/scroll_perf_test.dart',
91 92 93
  ).run;
}

94 95
TaskFunction createHomeScrollPerfTest() {
  return PerfTest(
96
    '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
97 98 99 100 101
    'test_driver/scroll_perf.dart',
    'home_scroll_perf',
  ).run;
}

102 103 104
TaskFunction createCullOpacityPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
105
    'test_driver/run_app.dart',
106
    'cull_opacity_perf',
107
    testDriver: 'test_driver/cull_opacity_perf_test.dart',
108 109 110
  ).run;
}

111
TaskFunction createCullOpacityPerfE2ETest() {
112
  return PerfTest.e2e(
113 114 115 116 117
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/cull_opacity_perf_e2e.dart',
  ).run;
}

118 119 120
TaskFunction createCubicBezierPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
121
    'test_driver/run_app.dart',
122
    'cubic_bezier_perf',
123
    testDriver: 'test_driver/cubic_bezier_perf_test.dart',
124
  ).run;
125 126
}

127 128 129 130 131 132 133
TaskFunction createCubicBezierPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/cubic_bezier_perf_e2e.dart',
  ).run;
}

134 135
TaskFunction createBackdropFilterPerfTest({
    bool measureCpuGpu = true,
136
    bool? enableImpeller,
137
}) {
138 139
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
140
    'test_driver/run_app.dart',
141
    'backdrop_filter_perf',
142
    measureCpuGpu: measureCpuGpu,
143
    testDriver: 'test_driver/backdrop_filter_perf_test.dart',
144
    saveTraceFile: true,
145
    enableImpeller: enableImpeller,
146 147 148
  ).run;
}

149 150 151 152 153 154 155 156 157 158 159
TaskFunction createAnimationWithMicrotasksPerfTest({bool measureCpuGpu = true}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'animation_with_microtasks_perf',
    measureCpuGpu: measureCpuGpu,
    testDriver: 'test_driver/animation_with_microtasks_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

160 161 162 163 164 165 166
TaskFunction createBackdropFilterPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/backdrop_filter_perf_e2e.dart',
  ).run;
}

167
TaskFunction createPostBackdropFilterPerfTest({bool measureCpuGpu = true}) {
168 169
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
170
    'test_driver/run_app.dart',
171
    'post_backdrop_filter_perf',
172
    measureCpuGpu: measureCpuGpu,
173
    testDriver: 'test_driver/post_backdrop_filter_perf_test.dart',
174
    saveTraceFile: true,
175 176 177
  ).run;
}

178 179
TaskFunction createSimpleAnimationPerfTest({
  bool measureCpuGpu = true,
180
  bool? enableImpeller,
181
}) {
182 183
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
184
    'test_driver/run_app.dart',
185
    'simple_animation_perf',
186
    measureCpuGpu: measureCpuGpu,
187
    testDriver: 'test_driver/simple_animation_perf_test.dart',
188
    saveTraceFile: true,
189
    enableImpeller: enableImpeller,
190
  ).run;
191 192
}

193 194 195 196 197 198 199
TaskFunction createAnimatedPlaceholderPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_placeholder_perf_e2e.dart',
  ).run;
}

200 201 202
TaskFunction createPictureCachePerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
203
    'test_driver/run_app.dart',
204
    'picture_cache_perf',
205
    testDriver: 'test_driver/picture_cache_perf_test.dart',
206 207 208
  ).run;
}

209
TaskFunction createPictureCachePerfE2ETest() {
210
  return PerfTest.e2e(
211 212 213 214 215
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/picture_cache_perf_e2e.dart',
  ).run;
}

216 217 218 219 220 221 222 223 224
TaskFunction createPictureCacheComplexityScoringPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'picture_cache_complexity_scoring_perf',
    testDriver: 'test_driver/picture_cache_complexity_scoring_perf_test.dart',
  ).run;
}

225 226 227 228 229 230 231 232 233 234 235
TaskFunction createOpenPayScrollPerfTest({bool measureCpuGpu = true}) {
  return PerfTest(
    openpayDirectory.path,
    'test_driver/scroll_perf.dart',
    'openpay_scroll_perf',
    measureCpuGpu: measureCpuGpu,
    testDriver: 'test_driver/scroll_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

236
TaskFunction createFlutterGalleryStartupTest({String target = 'lib/main.dart', Map<String, String>? runEnvironment}) {
237
  return StartupTest(
238
    '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
239
    target: target,
240
    runEnvironment: runEnvironment,
241
  ).run;
242 243
}

244
TaskFunction createComplexLayoutStartupTest() {
245
  return StartupTest(
246
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
247
  ).run;
248 249
}

250
TaskFunction createFlutterGalleryCompileTest() {
251
  return CompileTest('${flutterDirectory.path}/dev/integration_tests/flutter_gallery').run;
252 253
}

254
TaskFunction createHelloWorldCompileTest() {
255
  return CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run;
256 257
}

258 259 260 261
TaskFunction createWebCompileTest() {
  return const WebCompileTest().run;
}

262
TaskFunction createFlutterViewStartupTest() {
263
  return StartupTest(
264 265
      '${flutterDirectory.path}/examples/flutter_view',
      reportMetrics: false,
266 267 268
  ).run;
}

269
TaskFunction createPlatformViewStartupTest() {
270
  return StartupTest(
271 272 273 274 275
    '${flutterDirectory.path}/examples/platform_view',
    reportMetrics: false,
  ).run;
}

276 277 278 279 280
TaskFunction createBasicMaterialCompileTest() {
  return () async {
    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

281
    rmTree(sampleDir);
282

283
    await inDirectory<void>(Directory.systemTemp, () async {
284
      await flutter('create', options: <String>['--template=app', sampleAppName]);
285 286
    });

287
    if (!sampleDir.existsSync()) {
288
      throw 'Failed to create default Flutter app in ${sampleDir.path}';
289
    }
290

291
    return CompileTest(sampleDir.path).run();
292
  };
293 294
}

295 296 297
TaskFunction createTextfieldPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
298
    'test_driver/run_app.dart',
299
    'textfield_perf',
300
    testDriver: 'test_driver/textfield_perf_test.dart',
301 302 303
  ).run;
}

304 305 306 307 308 309 310
TaskFunction createTextfieldPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/textfield_perf_e2e.dart',
  ).run;
}

311 312 313 314 315 316 317
TaskFunction createVeryLongPictureScrollingPerfE2ETest({required bool enableImpeller}) {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/very_long_picture_scrolling_perf_e2e.dart',
    enableImpeller: enableImpeller,
  ).run;
}
318 319 320 321 322 323 324 325 326
TaskFunction createSlidersPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'sliders_perf',
    testDriver: 'test_driver/sliders_perf_test.dart',
  ).run;
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
TaskFunction createStackSizeTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks';
  const String testTarget = 'test_driver/run_app.dart';
  const String testDriver = 'test_driver/stack_size_perf_test.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
        '--no-android-gradle-daemon',
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '--driver', testDriver,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
350
        file('${_testOutputDirectory(testDirectory)}/stack_size.json').readAsStringSync(),
351 352 353 354 355 356 357 358 359 360 361 362 363
      ) as Map<String, dynamic>;

      final Map<String, dynamic> result = <String, dynamic>{
        'stack_size_per_nesting_level': data['stack_size'],
      };
      return TaskResult.success(
        result,
        benchmarkScoreKeys: result.keys.toList(),
      );
    });
  };
}

364 365 366 367 368 369 370 371 372
TaskFunction createFullscreenTextfieldPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'fullscreen_textfield_perf',
    testDriver: 'test_driver/fullscreen_textfield_perf_test.dart',
  ).run;
}

373
TaskFunction createFullscreenTextfieldPerfE2ETest({
374
  bool? enableImpeller,
375
}) {
376 377 378
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/fullscreen_textfield_perf_e2e.dart',
379
    enableImpeller: enableImpeller,
380 381 382
  ).run;
}

383 384 385 386 387 388 389
TaskFunction createClipperCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/clipper_cache_perf_e2e.dart',
  ).run;
}

390 391 392
TaskFunction createColorFilterAndFadePerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
393
    'test_driver/run_app.dart',
394
    'color_filter_and_fade_perf',
395
    testDriver: 'test_driver/color_filter_and_fade_perf_test.dart',
396
    saveTraceFile: true,
397 398 399
  ).run;
}

400
TaskFunction createColorFilterAndFadePerfE2ETest({bool? enableImpeller}) {
401 402 403
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_and_fade_perf_e2e.dart',
404
    enableImpeller: enableImpeller,
405 406 407
  ).run;
}

408 409 410 411 412 413 414
TaskFunction createColorFilterCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_cache_perf_e2e.dart',
  ).run;
}

415 416 417 418 419 420 421
TaskFunction createColorFilterWithUnstableChildPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/color_filter_with_unstable_child_perf_e2e.dart',
  ).run;
}

422 423 424 425 426 427 428
TaskFunction createRasterCacheUseMemoryPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/raster_cache_use_memory_perf_e2e.dart',
  ).run;
}

429 430 431 432 433 434 435
TaskFunction createShaderMaskCachePerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/shader_mask_cache_perf_e2e.dart',
  ).run;
}

436 437 438
TaskFunction createFadingChildAnimationPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
439
    'test_driver/run_app.dart',
440
    'fading_child_animation_perf',
441
    testDriver: 'test_driver/fading_child_animation_perf_test.dart',
442
    saveTraceFile: true,
443 444 445
  ).run;
}

446
TaskFunction createImageFilteredTransformAnimationPerfTest({
447
  bool? enableImpeller,
448
}) {
449 450
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
451
    'test_driver/run_app.dart',
452
    'imagefiltered_transform_animation_perf',
453
    testDriver: 'test_driver/imagefiltered_transform_animation_perf_test.dart',
454
    saveTraceFile: true,
455
    enableImpeller: enableImpeller,
456 457 458
  ).run;
}

459
TaskFunction createsMultiWidgetConstructPerfE2ETest() {
460
  return PerfTest.e2e(
461 462 463 464 465
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/multi_widget_construction_perf_e2e.dart',
  ).run;
}

466
TaskFunction createListTextLayoutPerfE2ETest({bool? enableImpeller}) {
467 468 469 470 471 472 473
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/list_text_layout_perf_e2e.dart',
    enableImpeller: enableImpeller,
  ).run;
}

Yuqian Li's avatar
Yuqian Li committed
474 475 476 477 478 479 480 481 482 483 484 485
TaskFunction createsScrollSmoothnessPerfTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/complex_layout';
  const String testTarget = 'test/measure_scroll_smoothness.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
486
        '--no-android-gradle-daemon',
Yuqian Li's avatar
Yuqian Li committed
487 488 489 490 491 492 493 494
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
495
        file('${_testOutputDirectory(testDirectory)}/scroll_smoothness_test.json').readAsStringSync(),
Yuqian Li's avatar
Yuqian Li committed
496 497 498 499 500
      ) as Map<String, dynamic>;

      final Map<String, dynamic> result = <String, dynamic>{};
      void addResult(dynamic data, String suffix) {
        assert(data is Map<String, dynamic>);
501 502 503 504 505 506 507 508 509
        if (data is Map<String, dynamic>) {
          const List<String> metricKeys = <String>[
            'janky_count',
            'average_abs_jerk',
            'dropped_frame_count',
          ];
          for (final String key in metricKeys) {
            result[key + suffix] = data[key];
          }
Yuqian Li's avatar
Yuqian Li committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        }
      }
      addResult(data['resample on with 90Hz input'], '_with_resampler_90Hz');
      addResult(data['resample on with 59Hz input'], '_with_resampler_59Hz');
      addResult(data['resample off with 90Hz input'], '_without_resampler_90Hz');
      addResult(data['resample off with 59Hz input'], '_without_resampler_59Hz');

      return TaskResult.success(
        result,
        benchmarkScoreKeys: result.keys.toList(),
      );
    });
  };
}

525 526 527 528 529 530 531 532 533 534 535 536
TaskFunction createFramePolicyIntegrationTest() {
  final String testDirectory =
      '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks';
  const String testTarget = 'test/frame_policy.dart';
  return () {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await device.unlock();
      final String deviceId = device.deviceId;
      await flutter('packages', options: <String>['get']);

      await flutter('drive', options: <String>[
537
        '--no-android-gradle-daemon',
538 539 540 541 542 543 544 545
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
546
        file('${_testOutputDirectory(testDirectory)}/frame_policy_event_delay.json').readAsStringSync(),
547 548 549
      ) as Map<String, dynamic>;
      final Map<String, dynamic> fullLiveData = data['fullyLive'] as Map<String, dynamic>;
      final Map<String, dynamic> benchmarkLiveData = data['benchmarkLive'] as Map<String, dynamic>;
550
      final Map<String, dynamic> dataFormatted = <String, dynamic>{
551 552 553 554 555 556 557 558 559 560 561
        'average_delay_fullyLive_millis':
          fullLiveData['average_delay_millis'],
        'average_delay_benchmarkLive_millis':
          benchmarkLiveData['average_delay_millis'],
        '90th_percentile_delay_fullyLive_millis':
          fullLiveData['90th_percentile_delay_millis'],
        '90th_percentile_delay_benchmarkLive_millis':
          benchmarkLiveData['90th_percentile_delay_millis'],
      };

      return TaskResult.success(
562 563
        dataFormatted,
        benchmarkScoreKeys: dataFormatted.keys.toList(),
564 565 566 567 568
      );
    });
  };
}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
TaskFunction createOpacityPeepholeOneRectPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_one_rect_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeColOfRowsPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_col_of_rows_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeOpacityOfGridPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_opacity_of_grid_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeGridOfOpacityPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_grid_of_opacity_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeFadeTransitionTextPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_fade_transition_text_perf_e2e.dart',
  ).run;
}

604 605 606 607 608 609 610 611 612 613 614 615 616 617
TaskFunction createOpacityPeepholeGridOfAlphaSaveLayersPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_grid_of_alpha_savelayers_perf_e2e.dart',
  ).run;
}

TaskFunction createOpacityPeepholeColOfAlphaSaveLayerRowsPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/opacity_peephole_col_of_alpha_savelayer_rows_perf_e2e.dart',
  ).run;
}

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
TaskFunction createGradientDynamicPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_dynamic_perf_e2e.dart',
  ).run;
}

TaskFunction createGradientConsistentPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_consistent_perf_e2e.dart',
  ).run;
}

TaskFunction createGradientStaticPerfE2ETest() {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/gradient_static_perf_e2e.dart',
  ).run;
}

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
TaskFunction createAnimatedAdvancedBlendPerfTest({
  bool? enableImpeller,
  bool? forceOpenGLES,
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'animated_advanced_blend_perf',
    enableImpeller: enableImpeller,
    forceOpenGLES: forceOpenGLES,
    testDriver: 'test_driver/animated_advanced_blend_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

654
TaskFunction createAnimatedBlurBackropFilterPerfTest({
655
  bool? enableImpeller,
656
  bool? forceOpenGLES,
657 658 659 660 661 662
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'animated_blur_backdrop_filter_perf',
    enableImpeller: enableImpeller,
663
    forceOpenGLES: forceOpenGLES,
664 665 666 667 668
    testDriver: 'test_driver/animated_blur_backdrop_filter_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

669 670 671 672 673 674 675 676 677 678 679 680 681
TaskFunction createDrawPointsPerfTest({
  bool? enableImpeller,
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'draw_points_perf',
    enableImpeller: enableImpeller,
    testDriver: 'test_driver/draw_points_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

682 683 684 685 686 687 688 689
TaskFunction createDrawAtlasPerfTest({
  bool? forceOpenGLES,
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'draw_atlas_perf',
    enableImpeller: true,
690
    testDriver: 'test_driver/draw_atlas_perf_test.dart',
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    saveTraceFile: true,
    forceOpenGLES: forceOpenGLES,
  ).run;
}

TaskFunction createDrawVerticesPerfTest({
  bool? forceOpenGLES,
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'draw_vertices_perf',
    enableImpeller: true,
    testDriver: 'test_driver/draw_vertices_perf_test.dart',
    saveTraceFile: true,
    forceOpenGLES: forceOpenGLES,
  ).run;
}

TaskFunction createPathTessellationStaticPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'tessellation_perf_static',
    enableImpeller: true,
    testDriver: 'test_driver/path_tessellation_static_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

TaskFunction createPathTessellationDynamicPerfTest() {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'tessellation_perf_dynamic',
    enableImpeller: true,
    testDriver: 'test_driver/path_tessellation_dynamic_perf_test.dart',
    saveTraceFile: true,
  ).run;
}

732
TaskFunction createAnimatedComplexOpacityPerfE2ETest({
733
  bool? enableImpeller,
734
}) {
735 736 737
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_complex_opacity_perf_e2e.dart',
738
    enableImpeller: enableImpeller,
739 740 741
  ).run;
}

742
TaskFunction createAnimatedComplexImageFilteredPerfE2ETest({
743
  bool? enableImpeller,
744 745 746 747 748 749 750 751 752
}) {
  return PerfTest.e2e(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test/animated_complex_image_filtered_perf_e2e.dart',
    enableImpeller: enableImpeller,
  ).run;
}


753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
Map<String, dynamic> _average(List<Map<String, dynamic>> results, int iterations) {
  final Map<String, dynamic> tally = <String, dynamic>{};
  for (final Map<String, dynamic> item in results) {
    item.forEach((String key, dynamic value) {
      if (tally.containsKey(key)) {
        tally[key] = (tally[key] as int) + (value as int);
      } else {
        tally[key] = value;
      }
    });
  }
  tally.forEach((String key, dynamic value) {
    tally[key] = (value as int) ~/ iterations;
  });
  return tally;
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
/// Opens the file at testDirectory + 'android/app/src/main/AndroidManifest.xml'
/// and adds the following entry to the application.
/// <meta-data
///   android:name="io.flutter.embedding.android.ImpellerBackend"
///   android:value="opengles" />
void _addOpenGLESToManifest(String testDirectory) {
  final String manifestPath = path.join(
      testDirectory, 'android', 'app', 'src', 'main', 'AndroidManifest.xml');
  final File file = File(manifestPath);

  if (!file.existsSync()) {
    throw Exception('AndroidManifest.xml not found at $manifestPath');
  }

  final String xmlStr = file.readAsStringSync();
  final XmlDocument xmlDoc = XmlDocument.parse(xmlStr);
  const String key = 'io.flutter.embedding.android.ImpellerBackend';
  const String value = 'opengles';

  final XmlElement applicationNode =
      xmlDoc.findAllElements('application').first;

  // Check if the meta-data node already exists.
  final Iterable<XmlElement> existingMetaData = applicationNode
      .findAllElements('meta-data')
      .where((XmlElement node) => node.getAttribute('android:name') == key);

  if (existingMetaData.isNotEmpty) {
    final XmlElement existingEntry = existingMetaData.first;
    existingEntry.setAttribute('android:value', value);
  } else {
    final XmlElement metaData = XmlElement(
      XmlName('meta-data'),
      <XmlAttribute>[
        XmlAttribute(XmlName('android:name'), key),
        XmlAttribute(XmlName('android:value'), value)
      ],
    );

    applicationNode.children.add(metaData);
  }

  file.writeAsStringSync(xmlDoc.toXmlString(pretty: true, indent: '    '));
}

Future<void> _resetManifest(String testDirectory) async {
  final String manifestPath = path.join(
      testDirectory, 'android', 'app', 'src', 'main', 'AndroidManifest.xml');
  final File file = File(manifestPath);

  if (!file.existsSync()) {
    throw Exception('AndroidManifest.xml not found at $manifestPath');
  }

  await exec('git', <String>['checkout', file.path]);
}

827 828
/// Measure application startup performance.
class StartupTest {
829 830 831 832 833 834
  const StartupTest(
    this.testDirectory, {
    this.reportMetrics = true,
    this.target = 'lib/main.dart',
    this.runEnvironment,
  });
835 836

  final String testDirectory;
837
  final bool reportMetrics;
838
  final String target;
839
  final Map<String, String>? runEnvironment;
840

841
  Future<TaskResult> run() async {
842
    return inDirectory<TaskResult>(testDirectory, () async {
843
      final Device device = await devices.workingDevice;
844
      await device.unlock();
845
      const int iterations = 5;
846
      final List<Map<String, dynamic>> results = <Map<String, dynamic>>[];
847 848

      section('Building application');
849
      String? applicationBinaryPath;
850 851 852 853 854 855 856
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.android:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm,android-arm64',
857
            '--target=$target',
858 859
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
860 861 862 863 864 865
        case DeviceOperatingSystem.androidArm:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm',
866
            '--target=$target',
867 868
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
869 870 871 872 873 874
        case DeviceOperatingSystem.androidArm64:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm64',
875
            '--target=$target',
876 877
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
878 879
        case DeviceOperatingSystem.fake:
        case DeviceOperatingSystem.fuchsia:
880
        case DeviceOperatingSystem.linux:
881
          break;
882
        case DeviceOperatingSystem.ios:
883
        case DeviceOperatingSystem.macos:
884
          await flutter('build', options: <String>[
885
            if (deviceOperatingSystem == DeviceOperatingSystem.ios) 'ios' else 'macos',
886 887
             '-v',
            '--profile',
888
            '--target=$target',
889
          ]);
890 891
          final String buildRoot = path.join(testDirectory, 'build');
          applicationBinaryPath = _findDarwinAppInBuildDirectory(buildRoot);
892
        case DeviceOperatingSystem.windows:
893 894 895 896 897 898 899 900 901 902 903
          await flutter('build', options: <String>[
            'windows',
            '-v',
            '--profile',
            '--target=$target',
          ]);
          final String basename = path.basename(testDirectory);
          applicationBinaryPath = path.join(
            testDirectory,
            'build',
            'windows',
904
            'x64',
905 906 907 908
            'runner',
            'Profile',
            '$basename.exe'
          );
909 910
      }

911 912
      const int maxFailures = 3;
      int currentFailures = 0;
913
      for (int i = 0; i < iterations; i += 1) {
914 915 916 917 918 919 920 921 922
        // Startup should not take more than a few minutes. After 10 minutes,
        // take a screenshot to help debug.
        final Timer timer = Timer(const Duration(minutes: 10), () async {
          print('Startup not completed within 10 minutes. Taking a screenshot...');
          await _flutterScreenshot(
            device.deviceId,
            'screenshot_startup_${DateTime.now().toLocal().toIso8601String()}.png',
          );
        });
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        final int result = await flutter(
          'run',
          options: <String>[
            '--no-android-gradle-daemon',
            '--no-publish-port',
            '--verbose',
            '--profile',
            '--trace-startup',
            // TODO(vashworth): Remove once done debugging https://github.com/flutter/flutter/issues/129836
            if (device is IosDevice)
              '--verbose-system-logs',
            '--target=$target',
            '-d',
            device.deviceId,
            if (applicationBinaryPath != null)
              '--use-application-binary=$applicationBinaryPath',
          ],
          environment: runEnvironment,
          canFail: true,
        );
943
        timer.cancel();
944 945
        if (result == 0) {
          final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
946
            file('${_testOutputDirectory(testDirectory)}/start_up_info.json').readAsStringSync(),
947 948 949 950
          ) as Map<String, dynamic>;
          results.add(data);
        } else {
          currentFailures += 1;
951 952 953 954
          await _flutterScreenshot(
            device.deviceId,
            'screenshot_startup_failure_$currentFailures.png',
          );
955 956 957 958 959
          i -= 1;
          if (currentFailures == maxFailures) {
            return TaskResult.failure('Application failed to start $maxFailures times');
          }
        }
960 961 962 963 964 965

        await flutter('install', options: <String>[
          '--uninstall-only',
          '-d',
          device.deviceId,
        ]);
966 967 968
      }

      final Map<String, dynamic> averageResults = _average(results, iterations);
969

970
      if (!reportMetrics) {
971
        return TaskResult.success(averageResults);
972
      }
973

974
      return TaskResult.success(averageResults, benchmarkScoreKeys: <String>[
975
        'timeToFirstFrameMicros',
976
        'timeToFirstFrameRasterizedMicros',
977 978 979
      ]);
    });
  }
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996

  Future<void> _flutterScreenshot(String deviceId, String screenshotName) async {
    if (hostAgent.dumpDirectory != null) {
      await flutter(
        'screenshot',
        options: <String>[
          '-d',
          deviceId,
          '--out',
          hostAgent.dumpDirectory!
              .childFile(screenshotName)
              .path,
        ],
        canFail: true,
      );
    }
  }
997 998
}

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
/// A one-off test to verify that devtools starts in profile mode.
class DevtoolsStartupTest {
  const DevtoolsStartupTest(this.testDirectory);

  final String testDirectory;

  Future<TaskResult> run() async {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;

      section('Building application');
1010
      String? applicationBinaryPath;
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.android:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm,android-arm64',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
        case DeviceOperatingSystem.androidArm:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
        case DeviceOperatingSystem.androidArm64:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm64',
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
        case DeviceOperatingSystem.ios:
          await flutter('build', options: <String>[
            'ios',
             '-v',
            '--profile',
          ]);
1042
          applicationBinaryPath = _findDarwinAppInBuildDirectory('$testDirectory/build/ios/iphoneos');
1043
        case DeviceOperatingSystem.fake:
1044
        case DeviceOperatingSystem.fuchsia:
1045
        case DeviceOperatingSystem.linux:
1046 1047
        case DeviceOperatingSystem.macos:
        case DeviceOperatingSystem.windows:
1048 1049 1050
          break;
      }

1051
      final Process process = await startFlutter(
1052
        'run',
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        options: <String>[
          '--no-android-gradle-daemon',
          '--no-publish-port',
          '--verbose',
          '--profile',
          '-d',
          device.deviceId,
          if (applicationBinaryPath != null)
            '--use-application-binary=$applicationBinaryPath',
       ],
      );
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
      final Completer<void> completer = Completer<void>();
      bool sawLine = false;
      process.stdout
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .listen((String line) {
          print('[STDOUT]: $line');
        // Wait for devtools output.
        if (line.contains('The Flutter DevTools debugger and profiler')) {
          sawLine = true;
          completer.complete();
        }
      });
      bool didExit = false;
      unawaited(process.exitCode.whenComplete(() {
        didExit = true;
      }));
      await Future.any(<Future<void>>[completer.future, Future<void>.delayed(const Duration(minutes: 5)), process.exitCode]);
      if (!didExit) {
        process.stdin.writeln('q');
        await process.exitCode;
      }

      await flutter('install', options: <String>[
        '--uninstall-only',
        '-d',
        device.deviceId,
      ]);

1093
      if (sawLine) {
1094
        return TaskResult.success(null, benchmarkScoreKeys: <String>[]);
1095
      }
1096 1097 1098 1099 1100
      return TaskResult.failure('Did not see line "The Flutter DevTools debugger and profiler" in output');
    });
  }
}

1101 1102 1103 1104 1105
/// A callback function to be used to mock the flutter drive command in PerfTests.
///
/// The `options` contains all the arguments in the `flutter drive` command in PerfTests.
typedef FlutterDriveCallback = void Function(List<String> options);

1106 1107 1108
/// Measures application runtime performance, specifically per-frame
/// performance.
class PerfTest {
1109
  const PerfTest(
1110 1111 1112
    this.testDirectory,
    this.testTarget,
    this.timelineFileName, {
1113
    this.measureCpuGpu = true,
1114
    this.measureMemory = true,
1115
    this.measureTotalGCTime = true,
1116
    this.saveTraceFile = false,
1117
    this.testDriver,
1118 1119
    this.needsFullTimeline = true,
    this.benchmarkScoreKeys,
1120
    this.dartDefine = '',
1121
    String? resultFilename,
1122 1123
    this.device,
    this.flutterDriveCallback,
1124
    this.timeoutSeconds,
1125
    this.enableImpeller,
1126
    this.forceOpenGLES,
1127 1128 1129 1130 1131
  }): _resultFilename = resultFilename;

  const PerfTest.e2e(
    this.testDirectory,
    this.testTarget, {
1132 1133
    this.measureCpuGpu = false,
    this.measureMemory = false,
1134
    this.measureTotalGCTime = false,
1135 1136 1137 1138 1139
    this.testDriver =  'test_driver/e2e_test.dart',
    this.needsFullTimeline = false,
    this.benchmarkScoreKeys = _kCommonScoreKeys,
    this.dartDefine = '',
    String resultFilename = 'e2e_perf_summary',
1140 1141
    this.device,
    this.flutterDriveCallback,
1142
    this.timeoutSeconds,
1143
    this.enableImpeller,
1144
    this.forceOpenGLES,
1145
  }) : saveTraceFile = false, timelineFileName = null, _resultFilename = resultFilename;
1146 1147

  /// The directory where the app under test is defined.
1148
  final String testDirectory;
1149
  /// The main entry-point file of the application, as run on the device.
1150
  final String testTarget;
1151
  // The prefix name of the filename such as `<timelineFileName>.timeline_summary.json`.
1152
  final String? timelineFileName;
1153
  String get traceFilename => '$timelineFileName.timeline';
1154
  String get resultFilename => _resultFilename ?? '$timelineFileName.timeline_summary';
1155
  final String? _resultFilename;
1156
  /// The test file to run on the host.
1157
  final String? testDriver;
1158
  /// Whether to collect CPU and GPU metrics.
1159
  final bool measureCpuGpu;
1160 1161
  /// Whether to collect memory metrics.
  final bool measureMemory;
1162 1163
  /// Whether to summarize total GC time on the UI thread from the timeline.
  final bool measureTotalGCTime;
1164 1165
  /// Whether to collect full timeline, meaning if `--trace-startup` flag is needed.
  final bool needsFullTimeline;
1166 1167
  /// Whether to save the trace timeline file `*.timeline.json`.
  final bool saveTraceFile;
1168 1169 1170 1171 1172 1173 1174 1175 1176
  /// The device to test on.
  ///
  /// If null, the device is selected depending on the current environment.
  final Device? device;

  /// The function called instead of the actually `flutter drive`.
  ///
  /// If it is not `null`, `flutter drive` will not happen in the PerfTests.
  final FlutterDriveCallback? flutterDriveCallback;
1177

1178
  /// Whether the perf test should enable Impeller.
1179
  final bool? enableImpeller;
1180

1181 1182 1183
  /// Whether the perf test force Impeller's OpenGLES backend.
  final bool? forceOpenGLES;

1184 1185 1186
  /// Number of seconds to time out the test after, allowing debug callbacks to run.
  final int? timeoutSeconds;

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  /// The keys of the values that need to be reported.
  ///
  /// If it's `null`, then report:
  /// ```Dart
  /// <String>[
  ///   'average_frame_build_time_millis',
  ///   'worst_frame_build_time_millis',
  ///   '90th_percentile_frame_build_time_millis',
  ///   '99th_percentile_frame_build_time_millis',
  ///   'average_frame_rasterizer_time_millis',
  ///   'worst_frame_rasterizer_time_millis',
  ///   '90th_percentile_frame_rasterizer_time_millis',
  ///   '99th_percentile_frame_rasterizer_time_millis',
  ///   'average_vsync_transitions_missed',
  ///   '90th_percentile_vsync_transitions_missed',
  ///   '99th_percentile_vsync_transitions_missed',
1203 1204
  ///   if (measureCpuGpu) 'average_cpu_usage',
  ///   if (measureCpuGpu) 'average_gpu_usage',
1205 1206
  /// ]
  /// ```
1207
  final List<String>? benchmarkScoreKeys;
1208

1209 1210 1211
  /// Additional flags for `--dart-define` to control the test
  final String dartDefine;

1212
  Future<TaskResult> run() {
1213 1214 1215 1216 1217
    return internalRun();
  }

  @protected
  Future<TaskResult> internalRun({
1218
      String? existingApp,
1219
  }) {
1220
    return inDirectory<TaskResult>(testDirectory, () async {
1221 1222 1223 1224 1225 1226 1227 1228
      late Device selectedDevice;
      if (device != null) {
        selectedDevice = device!;
      } else {
        selectedDevice = await devices.workingDevice;
      }
      await selectedDevice.unlock();
      final String deviceId = selectedDevice.deviceId;
1229
      final String? localEngine = localEngineFromEnv;
1230
      final String? localEngineHost = localEngineHostFromEnv;
1231
      final String? localEngineSrcPath = localEngineSrcPathFromEnv;
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
      Future<void> Function()? manifestReset;
      if (forceOpenGLES ?? false) {
        assert(enableImpeller!);
        _addOpenGLESToManifest(testDirectory);
        manifestReset = () => _resetManifest(testDirectory);
      }

      try {
        final List<String> options = <String>[
          if (localEngine != null) ...<String>['--local-engine', localEngine],
1243 1244 1245 1246
          if (localEngineHost != null) ...<String>[
            '--local-engine-host',
            localEngineHost
          ],
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
          if (localEngineSrcPath != null) ...<String>[
            '--local-engine-src-path',
            localEngineSrcPath
          ],
          '--no-dds',
          '--no-android-gradle-daemon',
          '-v',
          '--verbose-system-logs',
          '--profile',
          if (timeoutSeconds != null) ...<String>[
1257 1258 1259
            '--timeout',
            timeoutSeconds.toString(),
          ],
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
          if (needsFullTimeline)
            '--trace-startup', // Enables "endless" timeline event buffering.
          '-t', testTarget,
          if (testDriver != null) ...<String>['--driver', testDriver!],
          if (existingApp != null) ...<String>[
            '--use-existing-app',
            existingApp
          ],
          if (dartDefine.isNotEmpty) ...<String>['--dart-define', dartDefine],
          if (enableImpeller != null && enableImpeller!) '--enable-impeller',
          if (enableImpeller != null && !enableImpeller!)
            '--no-enable-impeller',
          '-d',
          deviceId,
        ];
        if (flutterDriveCallback != null) {
          flutterDriveCallback!(options);
        } else {
          await flutter('drive', options: options);
        }
      } finally {
        if (manifestReset != null) {
          await manifestReset();
        }
1284
      }
1285

1286
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
1287
        file('${_testOutputDirectory(testDirectory)}/$resultFilename.json').readAsStringSync(),
1288
      ) as Map<String, dynamic>;
1289

1290
      if (data['frame_count'] as int < 5) {
1291
        return TaskResult.failure(
1292 1293 1294 1295 1296
          'Timeline contains too few frames: ${data['frame_count']}. Possibly '
          'trace events are not being captured.',
        );
      }

1297 1298 1299
      // TODO(liyuqian): Remove isAndroid restriction once
      // https://github.com/flutter/flutter/issues/61567 is fixed.
      final bool isAndroid = deviceOperatingSystem == DeviceOperatingSystem.android;
1300 1301
      return TaskResult.success(
        data,
1302 1303
        detailFiles: <String>[
          if (saveTraceFile)
Dan Field's avatar
Dan Field committed
1304
            '${_testOutputDirectory(testDirectory)}/$traceFilename.json',
1305
        ],
1306
        benchmarkScoreKeys: benchmarkScoreKeys ?? <String>[
1307
          ..._kCommonScoreKeys,
1308 1309 1310
          'average_vsync_transitions_missed',
          '90th_percentile_vsync_transitions_missed',
          '99th_percentile_vsync_transitions_missed',
1311
          if (measureCpuGpu && !isAndroid) ...<String>[
1312 1313 1314
            // See https://github.com/flutter/flutter/issues/68888
            if (data['average_cpu_usage'] != null) 'average_cpu_usage',
            if (data['average_gpu_usage'] != null) 'average_gpu_usage',
1315 1316
          ],
          if (measureMemory && !isAndroid) ...<String>[
1317 1318
            // See https://github.com/flutter/flutter/issues/68888
            if (data['average_memory_usage'] != null) 'average_memory_usage',
1319 1320
            if (data['90th_percentile_memory_usage'] != null) '90th_percentile_memory_usage',
            if (data['99th_percentile_memory_usage'] != null) '99th_percentile_memory_usage',
1321
          ],
1322
          if (measureTotalGCTime) 'total_ui_gc_time',
1323 1324 1325 1326 1327 1328
          if (data['30hz_frame_percentage'] != null) '30hz_frame_percentage',
          if (data['60hz_frame_percentage'] != null) '60hz_frame_percentage',
          if (data['80hz_frame_percentage'] != null) '80hz_frame_percentage',
          if (data['90hz_frame_percentage'] != null) '90hz_frame_percentage',
          if (data['120hz_frame_percentage'] != null) '120hz_frame_percentage',
          if (data['illegal_refresh_rate_frame_count'] != null) 'illegal_refresh_rate_frame_count',
1329 1330
        ],
      );
1331 1332 1333 1334
    });
  }
}

1335 1336 1337 1338 1339 1340 1341 1342 1343
const List<String> _kCommonScoreKeys = <String>[
  'average_frame_build_time_millis',
  'worst_frame_build_time_millis',
  '90th_percentile_frame_build_time_millis',
  '99th_percentile_frame_build_time_millis',
  'average_frame_rasterizer_time_millis',
  'worst_frame_rasterizer_time_millis',
  '90th_percentile_frame_rasterizer_time_millis',
  '99th_percentile_frame_rasterizer_time_millis',
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
  'average_layer_cache_count',
  '90th_percentile_layer_cache_count',
  '99th_percentile_layer_cache_count',
  'worst_layer_cache_count',
  'average_layer_cache_memory',
  '90th_percentile_layer_cache_memory',
  '99th_percentile_layer_cache_memory',
  'worst_layer_cache_memory',
  'average_picture_cache_count',
  '90th_percentile_picture_cache_count',
  '99th_percentile_picture_cache_count',
  'worst_picture_cache_count',
  'average_picture_cache_memory',
  '90th_percentile_picture_cache_memory',
  '99th_percentile_picture_cache_memory',
  'worst_picture_cache_memory',
1360 1361
  'new_gen_gc_count',
  'old_gen_gc_count',
1362
];
1363

1364 1365 1366 1367 1368 1369 1370
/// Measures how long it takes to compile a Flutter app to JavaScript and how
/// big the compiled code is.
class WebCompileTest {
  const WebCompileTest();

  Future<TaskResult> run() async {
    final Map<String, Object> metrics = <String, Object>{};
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

    metrics.addAll(await runSingleBuildTest(
      directory: '${flutterDirectory.path}/examples/hello_world',
      metric: 'hello_world',
    ));

    metrics.addAll(await runSingleBuildTest(
      directory: '${flutterDirectory.path}/dev/integration_tests/flutter_gallery',
      metric: 'flutter_gallery',
    ));

    const String sampleAppName = 'sample_flutter_app';
    final Directory sampleDir = dir('${Directory.systemTemp.path}/$sampleAppName');

    rmTree(sampleDir);

    await inDirectory<void>(Directory.systemTemp, () async {
1388
      await flutter('create', options: <String>['--template=app', sampleAppName]);
1389
    });
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

    metrics.addAll(await runSingleBuildTest(
      directory: sampleDir.path,
      metric: 'basic_material_app',
    ));

    return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
  }

  /// Run a single web compile test and return its metrics.
  ///
  /// Run a single web compile test for the app under [directory], and store
  /// its metrics with prefix [metric].
1403 1404 1405 1406 1407
  static Future<Map<String, int>> runSingleBuildTest({
    required String directory,
    required String metric,
    bool measureBuildTime = false,
  }) {
1408 1409 1410
    return inDirectory<Map<String, int>>(directory, () async {
      final Map<String, int> metrics = <String, int>{};

1411
      await flutter('clean');
1412
      await flutter('packages', options: <String>['get']);
1413
      final Stopwatch? watch = measureBuildTime ? Stopwatch() : null;
1414
      watch?.start();
1415 1416 1417 1418 1419
      await evalFlutter('build', options: <String>[
        'web',
        '-v',
        '--release',
        '--no-pub',
1420
        '--no-web-resources-cdn',
1421
      ]);
1422
      watch?.stop();
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
      final String buildDir = path.join(directory, 'build', 'web');
      metrics.addAll(await getSize(
        directories: <String, String>{'web_build_dir': buildDir},
        files: <String, String>{
          'dart2js': path.join(buildDir, 'main.dart.js'),
          'canvaskit_wasm': path.join(buildDir, 'canvaskit', 'canvaskit.wasm'),
          'canvaskit_js': path.join(buildDir, 'canvaskit', 'canvaskit.js'),
          'flutter_js': path.join(buildDir, 'flutter.js'),
        },
        metric: metric,
      ));
1434

1435
      if (measureBuildTime) {
1436
        metrics['${metric}_dart2js_millis'] = watch!.elapsedMilliseconds;
1437
      }
1438

1439
      return metrics;
1440 1441 1442
    });
  }

1443 1444 1445 1446 1447 1448 1449 1450 1451
  /// Obtains the size and gzipped size of both [dartBundleFile] and [buildDir].
  static Future<Map<String, int>> getSize({
    /// Mapping of metric key name to file system path for directories to measure
    Map<String, String> directories = const <String, String>{},
    /// Mapping of metric key name to file system path for files to measure
    Map<String, String> files = const <String, String>{},
    required String metric,
  }) async {
    const String kGzipCompressionLevel = '-9';
1452 1453
    final Map<String, int> sizeMetrics = <String, int>{};

1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
    final Directory tempDir = Directory.systemTemp.createTempSync('perf_tests_gzips');
    try {
      for (final MapEntry<String, String> entry in files.entries) {
        final String key = entry.key;
        final String filePath = entry.value;
        sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(filePath).lengthSync();

        await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, filePath]);
        // gzip does not provide a CLI option to specify an output file, so
        // instead just move the output file to the temp dir
        final File compressedFile = File('$filePath.gz')
            .renameSync(path.join(tempDir.absolute.path, '$key.gz'));
        sizeMetrics['${metric}_${key}_compressed_bytes'] = compressedFile.lengthSync();
      }
1468

1469 1470 1471
      for (final MapEntry<String, String> entry in directories.entries) {
        final String key = entry.key;
        final String dirPath = entry.value;
1472

1473 1474 1475 1476 1477 1478 1479 1480
        final String tarball = path.join(tempDir.absolute.path, '$key.tar');
        await Process.run('tar', <String>[
          '--create',
          '--verbose',
          '--file=$tarball',
          dirPath,
        ]);
        sizeMetrics['${metric}_${key}_uncompressed_bytes'] = File(tarball).lengthSync();
1481

1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
        // get size of compressed build directory
        await Process.run('gzip',<String>['--keep', kGzipCompressionLevel, tarball]);
        sizeMetrics['${metric}_${key}_compressed_bytes'] = File('$tarball.gz').lengthSync();
      }
    } finally {
      try {
        tempDir.deleteSync(recursive: true);
      } on FileSystemException {
        print('Failed to delete ${tempDir.path}.');
      }
    }
    return sizeMetrics;
1494 1495 1496
  }
}

1497
/// Measures how long it takes to compile a Flutter app and how big the compiled
1498
/// code is.
1499
class CompileTest {
1500
  const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false });
1501 1502

  final String testDirectory;
1503
  final bool reportPackageContentSizes;
1504

1505
  Future<TaskResult> run() async {
1506
    return inDirectory<TaskResult>(testDirectory, () async {
1507
      await flutter('packages', options: <String>['get']);
1508

1509 1510 1511 1512 1513
      // "initial" compile required downloading and creating the `android/.gradle` directory while "full"
      // compiles only run `flutter clean` between runs.
      final Map<String, dynamic> compileInitialRelease = await _compileApp(deleteGradleCache: true);
      final Map<String, dynamic> compileFullRelease = await _compileApp(deleteGradleCache: false);
      final Map<String, dynamic> compileInitialDebug = await _compileDebug(
1514
        clean: true,
1515 1516 1517 1518 1519 1520
        deleteGradleCache: true,
        metricKey: 'debug_initial_compile_millis',
      );
      final Map<String, dynamic> compileFullDebug = await _compileDebug(
        clean: true,
        deleteGradleCache: false,
1521 1522 1523 1524 1525
        metricKey: 'debug_full_compile_millis',
      );
      // Build again without cleaning, should be faster.
      final Map<String, dynamic> compileSecondDebug = await _compileDebug(
        clean: false,
1526
        deleteGradleCache: false,
1527 1528 1529
        metricKey: 'debug_second_compile_millis',
      );

1530
      final Map<String, dynamic> metrics = <String, dynamic>{
1531 1532 1533 1534
        ...compileInitialRelease,
        ...compileFullRelease,
        ...compileInitialDebug,
        ...compileFullDebug,
1535
        ...compileSecondDebug,
1536
      };
1537

1538 1539 1540 1541 1542 1543 1544 1545
      final File mainDart = File('$testDirectory/lib/main.dart');
      if (mainDart.existsSync()) {
        final List<int> bytes = mainDart.readAsBytesSync();
        // "Touch" the file
        mainDart.writeAsStringSync(' ', mode: FileMode.append, flush: true);
        // Build after "edit" without clean should be faster than first build
        final Map<String, dynamic> compileAfterEditDebug = await _compileDebug(
          clean: false,
1546
          deleteGradleCache: false,
1547 1548 1549 1550 1551 1552 1553
          metricKey: 'debug_compile_after_edit_millis',
        );
        metrics.addAll(compileAfterEditDebug);
        // Revert the changes
        mainDart.writeAsBytesSync(bytes, flush: true);
      }

1554
      return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
1555 1556
    });
  }
1557

1558
  Future<Map<String, dynamic>> _compileApp({required bool deleteGradleCache}) async {
1559
    await flutter('clean');
1560 1561 1562 1563
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1564
    final Stopwatch watch = Stopwatch();
1565 1566
    int releaseSizeInBytes;
    final List<String> options = <String>['--release'];
1567 1568
    final Map<String, dynamic> metrics = <String, dynamic>{};

Ian Hickson's avatar
Ian Hickson committed
1569 1570
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
      case DeviceOperatingSystem.macos:
        unawaited(stderr.flush());
        late final String deviceId;
        if (deviceOperatingSystem == DeviceOperatingSystem.ios) {
          deviceId = 'ios';
        } else if (deviceOperatingSystem == DeviceOperatingSystem.macos) {
          deviceId = 'macos';
        } else {
          throw Exception('Attempted to run darwin compile workflow with $deviceOperatingSystem');
        }

        options.insert(0, deviceId);
1583 1584
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1585 1586 1587
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1588 1589 1590 1591
        final Directory buildDirectory = dir(path.join(
          cwd,
          'build',
        ));
1592
        final String? appPath =
1593
            _findDarwinAppInBuildDirectory(buildDirectory.path);
1594
        if (appPath == null) {
1595
          throw 'Failed to find app bundle in ${buildDirectory.path}';
1596
        }
1597 1598 1599 1600
        // Validate changes in Dart snapshot format and data layout do not
        // change compression size. This also simulates the size of an IPA on iOS.
        await exec('tar', <String>['-zcf', 'build/app.tar.gz', appPath]);
        releaseSizeInBytes = await file('$cwd/build/app.tar.gz').length();
1601
        if (reportPackageContentSizes) {
1602
          final Map<String, Object> sizeMetrics = await getSizesFromDarwinApp(
1603 1604
            appPath: appPath,
            operatingSystem: deviceOperatingSystem,
1605 1606
          );
          metrics.addAll(sizeMetrics);
1607
        }
Ian Hickson's avatar
Ian Hickson committed
1608
      case DeviceOperatingSystem.android:
1609
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1610
        options.insert(0, 'apk');
1611
        options.add('--target-platform=android-arm');
1612
        options.add('--tree-shake-icons');
1613
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1614 1615 1616
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1617 1618
        final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk';
        final File apk = file(apkPath);
1619
        releaseSizeInBytes = apk.lengthSync();
1620
        if (reportPackageContentSizes) {
1621
          metrics.addAll(await getSizesFromApk(apkPath));
1622
        }
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
      case DeviceOperatingSystem.androidArm64:
        options.insert(0, 'apk');
        options.add('--target-platform=android-arm64');
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
        watch.start();
        await flutter('build', options: options);
        watch.stop();
        final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk';
        final File apk = file(apkPath);
        releaseSizeInBytes = apk.lengthSync();
1634
        if (reportPackageContentSizes) {
1635
          metrics.addAll(await getSizesFromApk(apkPath));
1636
        }
1637 1638
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1639 1640
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
1641 1642
      case DeviceOperatingSystem.linux:
        throw Exception('Unsupported option for Linux devices');
1643
      case DeviceOperatingSystem.windows:
1644 1645 1646 1647 1648 1649 1650
        unawaited(stderr.flush());
        options.insert(0, 'windows');
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1651 1652
        final String basename = path.basename(cwd);
        final String exePath = path.join(
1653 1654 1655
          cwd,
          'build',
          'windows',
1656
          'x64',
1657 1658
          'runner',
          'release',
1659 1660
          '$basename.exe');
        final File exe = file(exePath);
1661
        // On Windows, we do not produce a single installation package file,
1662 1663 1664
        // rather a directory containing an .exe and .dll files.
        // The release size is set to the size of the produced .exe file
        releaseSizeInBytes = exe.lengthSync();
1665
    }
1666

1667
    metrics.addAll(<String, dynamic>{
1668
      'release_${deleteGradleCache ? 'initial' : 'full'}_compile_millis': watch.elapsedMilliseconds,
1669
      'release_size_bytes': releaseSizeInBytes,
1670 1671 1672
    });

    return metrics;
1673 1674
  }

1675 1676
  Future<Map<String, dynamic>> _compileDebug({
    required bool deleteGradleCache,
1677 1678
    required bool clean,
    required String metricKey,
1679 1680 1681 1682
  }) async {
    if (clean) {
      await flutter('clean');
    }
1683 1684 1685 1686
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1687
    final Stopwatch watch = Stopwatch();
Ian Hickson's avatar
Ian Hickson committed
1688 1689 1690 1691 1692
    final List<String> options = <String>['--debug'];
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
      case DeviceOperatingSystem.android:
1693
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1694
        options.insert(0, 'apk');
1695
        options.add('--target-platform=android-arm');
1696 1697 1698
      case DeviceOperatingSystem.androidArm64:
        options.insert(0, 'apk');
        options.add('--target-platform=android-arm64');
1699 1700
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1701 1702
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
1703 1704
      case DeviceOperatingSystem.linux:
        throw Exception('Unsupported option for Linux devices');
1705
      case DeviceOperatingSystem.macos:
1706 1707
        unawaited(stderr.flush());
        options.insert(0, 'macos');
1708
      case DeviceOperatingSystem.windows:
1709 1710
        unawaited(stderr.flush());
        options.insert(0, 'windows');
1711
    }
Ian Hickson's avatar
Ian Hickson committed
1712 1713 1714
    watch.start();
    await flutter('build', options: options);
    watch.stop();
1715 1716

    return <String, dynamic>{
1717
      metricKey: watch.elapsedMilliseconds,
1718 1719 1720
    };
  }

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  static Future<Map<String, Object>> getSizesFromDarwinApp({
    required String appPath,
    required DeviceOperatingSystem operatingSystem,
  }) async {
    late final File flutterFramework;
    late final String frameworkDirectory;
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        frameworkDirectory = path.join(
          appPath,
          'Frameworks',
        );
        flutterFramework = File(path.join(
          frameworkDirectory,
          'Flutter.framework',
          'Flutter',
        ));
      case DeviceOperatingSystem.macos:
        frameworkDirectory = path.join(
          appPath,
          'Contents',
          'Frameworks',
        );
        flutterFramework = File(path.join(
          frameworkDirectory,
          'FlutterMacOS.framework',
          'FlutterMacOS',
        )); // https://github.com/flutter/flutter/issues/70413
      case DeviceOperatingSystem.android:
      case DeviceOperatingSystem.androidArm:
      case DeviceOperatingSystem.androidArm64:
      case DeviceOperatingSystem.fake:
      case DeviceOperatingSystem.fuchsia:
1754
      case DeviceOperatingSystem.linux:
1755 1756 1757
      case DeviceOperatingSystem.windows:
        throw Exception('Called ${CompileTest.getSizesFromDarwinApp} with $operatingSystem.');
    }
1758

1759 1760 1761 1762 1763
    final File appFramework = File(path.join(
      frameworkDirectory,
      'App.framework',
      'App',
    ));
1764

1765
    return <String, Object>{
1766 1767 1768 1769 1770
      'app_framework_uncompressed_bytes': await appFramework.length(),
      'flutter_framework_uncompressed_bytes': await flutterFramework.length(),
    };
  }

1771 1772 1773 1774 1775 1776 1777
  static Future<Map<String, dynamic>> getSizesFromApk(String apkPath) async {
    final  String output = await eval('unzip', <String>['-v', apkPath]);
    final List<String> lines = output.split('\n');
    final Map<String, _UnzipListEntry> fileToMetadata = <String, _UnzipListEntry>{};

    // First three lines are header, last two lines are footer.
    for (int i = 3; i < lines.length - 2; i++) {
1778
      final _UnzipListEntry entry = _UnzipListEntry.fromLine(lines[i]);
1779 1780 1781
      fileToMetadata[entry.path] = entry;
    }

1782 1783 1784
    final _UnzipListEntry libflutter = fileToMetadata['lib/armeabi-v7a/libflutter.so']!;
    final _UnzipListEntry libapp = fileToMetadata['lib/armeabi-v7a/libapp.so']!;
    final _UnzipListEntry license = fileToMetadata['assets/flutter_assets/NOTICES.Z']!;
1785 1786 1787 1788

    return <String, dynamic>{
      'libflutter_uncompressed_bytes': libflutter.uncompressedSize,
      'libflutter_compressed_bytes': libflutter.compressedSize,
1789 1790
      'libapp_uncompressed_bytes': libapp.uncompressedSize,
      'libapp_compressed_bytes': libapp.compressedSize,
1791 1792
      'license_uncompressed_bytes': license.uncompressedSize,
      'license_compressed_bytes': license.compressedSize,
1793 1794
    };
  }
1795
}
1796

1797
/// Measure application memory usage.
1798
class MemoryTest {
1799 1800 1801 1802 1803 1804 1805 1806
  MemoryTest(this.project, this.test, this.package);

  final String project;
  final String test;
  final String package;

  /// Completes when the log line specified in the last call to
  /// [prepareForNextMessage] is seen by `adb logcat`.
1807 1808 1809
  Future<void>? get receivedNextMessage => _receivedNextMessage?.future;
  Completer<void>? _receivedNextMessage;
  String? _nextMessage;
1810 1811 1812 1813 1814

  /// Prepares the [receivedNextMessage] future such that it will complete
  /// when `adb logcat` sees a log line with the given `message`.
  void prepareForNextMessage(String message) {
    _nextMessage = message;
1815
    _receivedNextMessage = Completer<void>();
1816
  }
1817

1818
  int get iterationCount => 10;
1819

1820 1821
  Device? get device => _device;
  Device? _device;
1822

1823
  Future<TaskResult> run() {
1824
    return inDirectory<TaskResult>(project, () async {
1825 1826 1827 1828
      // This test currently only works on Android, because device.logcat,
      // device.getMemoryStats, etc, aren't implemented for iOS.

      _device = await devices.workingDevice;
1829
      await device!.unlock();
1830 1831
      await flutter('packages', options: <String>['get']);

1832
      final StreamSubscription<String> adb = device!.logcat.listen(
1833
        (String data) {
1834
          if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) {
1835
            _receivedNextMessage?.complete();
1836
          }
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
        },
      );

      for (int iteration = 0; iteration < iterationCount; iteration += 1) {
        print('running memory test iteration $iteration...');
        _startMemoryUsage = null;
        await useMemory();
        assert(_startMemoryUsage != null);
        assert(_startMemory.length == iteration + 1);
        assert(_endMemory.length == iteration + 1);
        assert(_diffMemory.length == iteration + 1);
        print('terminating...');
1849
        await device!.stop(package);
1850
        await Future<void>.delayed(const Duration(milliseconds: 10));
1851
      }
1852

1853
      await adb.cancel();
1854
      await flutter('install', options: <String>['--uninstall-only', '-d', device!.deviceId]);
1855

1856 1857 1858
      final ListStatistics startMemoryStatistics = ListStatistics(_startMemory);
      final ListStatistics endMemoryStatistics = ListStatistics(_endMemory);
      final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory);
1859

1860 1861 1862 1863 1864
      final Map<String, dynamic> memoryUsage = <String, dynamic>{
        ...startMemoryStatistics.asMap('start'),
        ...endMemoryStatistics.asMap('end'),
        ...diffMemoryStatistics.asMap('diff'),
      };
1865

1866 1867 1868 1869 1870
      _device = null;
      _startMemory.clear();
      _endMemory.clear();
      _diffMemory.clear();

1871
      return TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList());
1872 1873
    });
  }
1874

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
  /// Starts the app specified by [test] on the [device].
  ///
  /// The [run] method will terminate it by its package name ([package]).
  Future<void> launchApp() async {
    prepareForNextMessage('READY');
    print('launching $project$test on device...');
    await flutter('run', options: <String>[
      '--verbose',
      '--release',
      '--no-resident',
1885
      '-d', device!.deviceId,
1886 1887 1888 1889 1890
      test,
    ]);
    print('awaiting "ready" message...');
    await receivedNextMessage;
  }
1891

1892
  /// To change the behavior of the test, override this.
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
  ///
  /// Make sure to call recordStart() and recordEnd() once each in that order.
  ///
  /// By default it just launches the app, records memory usage, taps the device,
  /// awaits a DONE notification, and records memory usage again.
  Future<void> useMemory() async {
    await launchApp();
    await recordStart();

    prepareForNextMessage('DONE');
    print('tapping device...');
1904
    await device!.tap(100, 100);
1905 1906 1907 1908 1909
    print('awaiting "done" message...');
    await receivedNextMessage;

    await recordEnd();
  }
1910

1911 1912 1913
  final List<int> _startMemory = <int>[];
  final List<int> _endMemory = <int>[];
  final List<int> _diffMemory = <int>[];
1914

1915
  Map<String, dynamic>? _startMemoryUsage;
1916

1917 1918 1919 1920
  @protected
  Future<void> recordStart() async {
    assert(_startMemoryUsage == null);
    print('snapshotting memory usage...');
1921
    _startMemoryUsage = await device!.getMemoryStats(package);
1922
  }
1923

1924 1925 1926 1927
  @protected
  Future<void> recordEnd() async {
    assert(_startMemoryUsage != null);
    print('snapshotting memory usage...');
1928 1929
    final Map<String, dynamic> endMemoryUsage = await device!.getMemoryStats(package);
    _startMemory.add(_startMemoryUsage!['total_kb'] as int);
1930
    _endMemory.add(endMemoryUsage['total_kb'] as int);
1931
    _diffMemory.add((endMemoryUsage['total_kb'] as int) - (_startMemoryUsage!['total_kb'] as int));
1932 1933
  }
}
1934

1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
class DevToolsMemoryTest {
  DevToolsMemoryTest(this.project, this.driverTest);

  final String project;
  final String driverTest;

  Future<TaskResult> run() {
    return inDirectory<TaskResult>(project, () async {
      _device = await devices.workingDevice;
      await _device.unlock();

      await flutter(
        'drive',
        options: <String>[
          '-d', _device.deviceId,
          '--profile',
1951 1952 1953
          '--profile-memory', _kJsonFileName,
          '--no-publish-port',
          '-v',
1954 1955 1956 1957 1958 1959 1960
          driverTest,
        ],
      );

      final Map<String, dynamic> data = json.decode(
        file('$project/$_kJsonFileName').readAsStringSync(),
      ) as Map<String, dynamic>;
1961
      final List<dynamic> samples = (data['samples'] as Map<String, dynamic>)['data'] as List<dynamic>;
1962 1963
      int maxRss = 0;
      int maxAdbTotal = 0;
1964
      for (final Map<String, dynamic> sample in samples.cast<Map<String, dynamic>>()) {
1965 1966 1967
        if (sample['rss'] != null) {
          maxRss = math.max(maxRss, sample['rss'] as int);
        }
1968
        if (sample['adb_memoryInfo'] != null) {
1969
          maxAdbTotal = math.max(maxAdbTotal, (sample['adb_memoryInfo'] as Map<String, dynamic>)['Total'] as int);
1970 1971
        }
      }
1972

1973
      return TaskResult.success(
1974 1975
        <String, dynamic>{'maxRss': maxRss, 'maxAdbTotal': maxAdbTotal},
        benchmarkScoreKeys: <String>['maxRss', 'maxAdbTotal'],
1976 1977 1978 1979
      );
    });
  }

1980
  late Device _device;
1981 1982 1983 1984

  static const String _kJsonFileName = 'devtools_memory.json';
}

1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
enum ReportedDurationTestFlavor {
  debug, profile, release
}

String _reportedDurationTestToString(ReportedDurationTestFlavor flavor) {
  switch (flavor) {
    case ReportedDurationTestFlavor.debug:
      return 'debug';
    case ReportedDurationTestFlavor.profile:
      return 'profile';
    case ReportedDurationTestFlavor.release:
      return 'release';
  }
}

2000
class ReportedDurationTest {
2001
  ReportedDurationTest(this.flavor, this.project, this.test, this.package, this.durationPattern);
2002

2003
  final ReportedDurationTestFlavor flavor;
2004 2005 2006 2007 2008 2009 2010 2011 2012
  final String project;
  final String test;
  final String package;
  final RegExp durationPattern;

  final Completer<int> durationCompleter = Completer<int>();

  int get iterationCount => 10;

2013 2014
  Device? get device => _device;
  Device? _device;
2015 2016 2017 2018 2019 2020 2021

  Future<TaskResult> run() {
    return inDirectory<TaskResult>(project, () async {
      // This test currently only works on Android, because device.logcat,
      // device.getMemoryStats, etc, aren't implemented for iOS.

      _device = await devices.workingDevice;
2022
      await device!.unlock();
2023 2024
      await flutter('packages', options: <String>['get']);

2025
      final StreamSubscription<String> adb = device!.logcat.listen(
2026
        (String data) {
2027
          if (durationPattern.hasMatch(data)) {
2028
            durationCompleter.complete(int.parse(durationPattern.firstMatch(data)!.group(1)!));
2029
          }
2030 2031 2032 2033 2034
        },
      );
      print('launching $project$test on device...');
      await flutter('run', options: <String>[
        '--verbose',
2035
        '--no-publish-port',
2036
        '--no-fast-start',
2037
        '--${_reportedDurationTestToString(flavor)}',
2038
        '--no-resident',
2039
        '-d', device!.deviceId,
2040 2041 2042 2043 2044
        test,
      ]);

      final int duration = await durationCompleter.future;
      print('terminating...');
2045
      await device!.stop(package);
2046 2047 2048 2049 2050
      await adb.cancel();

      _device = null;

      final Map<String, dynamic> reportedDuration = <String, dynamic>{
2051
        'duration': duration,
2052 2053 2054 2055 2056 2057 2058 2059
      };
      _device = null;

      return TaskResult.success(reportedDuration, benchmarkScoreKeys: reportedDuration.keys.toList());
    });
  }
}

2060 2061 2062 2063
/// Holds simple statistics of an odd-lengthed list of integers.
class ListStatistics {
  factory ListStatistics(Iterable<int> data) {
    assert(data.isNotEmpty);
2064
    assert(data.length.isOdd);
2065
    final List<int> sortedData = data.toList()..sort();
2066
    return ListStatistics._(
2067 2068 2069 2070 2071
      sortedData.first,
      sortedData.last,
      sortedData[(sortedData.length - 1) ~/ 2],
    );
  }
2072

2073
  const ListStatistics._(this.min, this.max, this.median);
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
  final int min;
  final int max;
  final int median;

  Map<String, int> asMap(String prefix) {
    return <String, int>{
      '$prefix-min': min,
      '$prefix-max': max,
      '$prefix-median': median,
    };
2085 2086
  }
}
2087 2088 2089

class _UnzipListEntry {
  factory _UnzipListEntry.fromLine(String line) {
2090
    final List<String> data = line.trim().split(RegExp(r'\s+'));
2091
    assert(data.length == 8);
2092
    return _UnzipListEntry._(
2093 2094 2095 2096 2097 2098 2099
      uncompressedSize:  int.parse(data[0]),
      compressedSize: int.parse(data[2]),
      path: data[7],
    );
  }

  _UnzipListEntry._({
2100 2101 2102
    required this.uncompressedSize,
    required this.compressedSize,
    required this.path,
2103
  }) : assert(compressedSize <= uncompressedSize);
2104 2105 2106 2107 2108

  final int uncompressedSize;
  final int compressedSize;
  final String path;
}
2109

2110
/// Wait for up to 1 hour for the file to appear.
2111
Future<File> waitForFile(String path) async {
2112
  for (int i = 0; i < 180; i += 1) {
2113 2114 2115 2116 2117 2118 2119
    final File file = File(path);
    print('looking for ${file.path}');
    if (file.existsSync()) {
      return file;
    }
    await Future<void>.delayed(const Duration(seconds: 20));
  }
2120
  throw StateError('Did not find vmservice out file after 1 hour');
2121 2122
}

2123 2124 2125
String? _findDarwinAppInBuildDirectory(String searchDirectory) {
  for (final FileSystemEntity entity in Directory(searchDirectory)
    .listSync(recursive: true)) {
2126 2127 2128 2129 2130 2131
    if (entity.path.endsWith('.app')) {
      return entity.path;
    }
  }
  return null;
}