perf_tests.dart 73.5 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
  bool forceOpenGLES = false,
32
}) {
33
  return PerfTest(
34
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
35 36 37
    badScroll
      ? 'test_driver/scroll_perf_bad.dart'
      : 'test_driver/scroll_perf.dart',
38
    'complex_layout_scroll_perf',
39
    measureCpuGpu: measureCpuGpu,
40
    enableImpeller: enableImpeller,
41
    forceOpenGLES: forceOpenGLES,
42
  ).run;
43 44
}

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

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

65
TaskFunction createUiKitViewScrollPerfNonIntersectingTest({bool? enableImpeller}) {
66 67 68 69 70 71 72 73 74 75
  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;
}

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

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

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

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

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

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

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

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

152 153 154 155 156 157 158 159 160 161 162
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;
}

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

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

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

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

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

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

219 220 221 222 223 224 225 226 227
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;
}

228 229 230 231 232 233 234 235 236 237 238
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;
}

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

247
TaskFunction createComplexLayoutStartupTest() {
248
  return StartupTest(
249
    '${flutterDirectory.path}/dev/benchmarks/complex_layout',
250
  ).run;
251 252
}

253
TaskFunction createFlutterGalleryCompileTest() {
254
  return CompileTest('${flutterDirectory.path}/dev/integration_tests/flutter_gallery').run;
255 256
}

257
TaskFunction createHelloWorldCompileTest() {
258
  return CompileTest('${flutterDirectory.path}/examples/hello_world', reportPackageContentSizes: true).run;
259 260
}

261 262 263 264
TaskFunction createWebCompileTest() {
  return const WebCompileTest().run;
}

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

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

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

284
    rmTree(sampleDir);
285

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

290
    if (!sampleDir.existsSync()) {
291
      throw 'Failed to create default Flutter app in ${sampleDir.path}';
292
    }
293

294
    return CompileTest(sampleDir.path).run();
295
  };
296 297
}

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

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

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

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
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
353
        file('${_testOutputDirectory(testDirectory)}/stack_size.json').readAsStringSync(),
354 355 356 357 358 359 360 361 362 363 364 365 366
      ) 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(),
      );
    });
  };
}

367 368 369 370 371 372 373 374 375
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;
}

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

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

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

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

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

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

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

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

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

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

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

469
TaskFunction createListTextLayoutPerfE2ETest({bool? enableImpeller}) {
470 471 472 473 474 475 476
  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
477 478 479 480 481 482 483 484 485 486 487 488
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>[
489
        '--no-android-gradle-daemon',
Yuqian Li's avatar
Yuqian Li committed
490 491 492 493 494 495 496 497
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
498
        file('${_testOutputDirectory(testDirectory)}/scroll_smoothness_test.json').readAsStringSync(),
Yuqian Li's avatar
Yuqian Li committed
499 500 501 502 503
      ) as Map<String, dynamic>;

      final Map<String, dynamic> result = <String, dynamic>{};
      void addResult(dynamic data, String suffix) {
        assert(data is Map<String, dynamic>);
504 505 506 507 508 509 510 511 512
        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
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
        }
      }
      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(),
      );
    });
  };
}

528 529 530 531 532 533 534 535 536 537 538 539
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>[
540
        '--no-android-gradle-daemon',
541 542 543 544 545 546 547 548
        '-v',
        '--verbose-system-logs',
        '--profile',
        '-t', testTarget,
        '-d',
        deviceId,
      ]);
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
549
        file('${_testOutputDirectory(testDirectory)}/frame_policy_event_delay.json').readAsStringSync(),
550 551 552
      ) 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>;
553
      final Map<String, dynamic> dataFormatted = <String, dynamic>{
554 555 556 557 558 559 560 561 562 563 564
        '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(
565 566
        dataFormatted,
        benchmarkScoreKeys: dataFormatted.keys.toList(),
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 604 605 606
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;
}

607 608 609 610 611 612 613 614 615 616 617 618 619 620
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;
}

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
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;
}

642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
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;
}

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

672 673 674 675 676 677 678 679 680 681 682 683 684
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;
}

685 686 687 688 689 690 691 692
TaskFunction createDrawAtlasPerfTest({
  bool? forceOpenGLES,
}) {
  return PerfTest(
    '${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
    'test_driver/run_app.dart',
    'draw_atlas_perf',
    enableImpeller: true,
693
    testDriver: 'test_driver/draw_atlas_perf_test.dart',
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 732 733 734
    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;
}

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

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


756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
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;
}

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
/// Opens the file at testDirectory + 'ios/Runner/Info.plist'
/// and adds the following entry to the application.
/// <FTLDisablePartialRepaint/>
/// <true/>
void _disablePartialRepaint(String testDirectory) {
  final String manifestPath = path.join(
      testDirectory, 'ios', 'Runner', 'Info.plist');
  final File file = File(manifestPath);

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

  final String xmlStr = file.readAsStringSync();
  final XmlDocument xmlDoc = XmlDocument.parse(xmlStr);
  final List<(String, String)> keyPairs = <(String, String)>[
    ('FLTDisablePartialRepaint', 'true'),
  ];

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

  // Check if the meta-data node already exists.
  for (final (String key, String value) in keyPairs) {
    applicationNode.children.add(XmlElement(XmlName('key'), <XmlAttribute>[], <XmlNode>[
      XmlText(key)
    ], false));
    applicationNode.children.add(XmlElement(XmlName(value)));
  }

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

Future<void> _resetPlist(String testDirectory) async {
  final String manifestPath = path.join(
      testDirectory, 'ios', 'Runner', 'Info.plist');
  final File file = File(manifestPath);

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

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

818 819 820 821 822
/// 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" />
823 824 825
/// <meta-data
///   android:name="io.flutter.embedding.android.EnableOpenGLGPUTracing"
///   android:value="true" />
826 827 828 829 830 831 832 833 834 835 836
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);
837 838 839 840
  final List<(String, String)> keyPairs = <(String, String)>[
    ('io.flutter.embedding.android.ImpellerBackend', 'opengles'),
    ('io.flutter.embedding.android.EnableOpenGLGPUTracing', 'true')
  ];
841 842 843 844 845

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

  // Check if the meta-data node already exists.
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
  for (final (String key, String value) in keyPairs) {
    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);
    }
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
  }

  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]);
}

882 883
/// Measure application startup performance.
class StartupTest {
884 885 886 887 888 889
  const StartupTest(
    this.testDirectory, {
    this.reportMetrics = true,
    this.target = 'lib/main.dart',
    this.runEnvironment,
  });
890 891

  final String testDirectory;
892
  final bool reportMetrics;
893
  final String target;
894
  final Map<String, String>? runEnvironment;
895

896
  Future<TaskResult> run() async {
897
    return inDirectory<TaskResult>(testDirectory, () async {
898
      final Device device = await devices.workingDevice;
899
      await device.unlock();
900
      const int iterations = 5;
901
      final List<Map<String, dynamic>> results = <Map<String, dynamic>>[];
902 903

      section('Building application');
904
      String? applicationBinaryPath;
905 906 907 908 909 910 911
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.android:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm,android-arm64',
912
            '--target=$target',
913 914
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
915 916 917 918 919 920
        case DeviceOperatingSystem.androidArm:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm',
921
            '--target=$target',
922 923
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
924 925 926 927 928 929
        case DeviceOperatingSystem.androidArm64:
          await flutter('build', options: <String>[
            'apk',
            '-v',
            '--profile',
            '--target-platform=android-arm64',
930
            '--target=$target',
931 932
          ]);
          applicationBinaryPath = '$testDirectory/build/app/outputs/flutter-apk/app-profile.apk';
933 934
        case DeviceOperatingSystem.fake:
        case DeviceOperatingSystem.fuchsia:
935
        case DeviceOperatingSystem.linux:
936
          break;
937
        case DeviceOperatingSystem.ios:
938
        case DeviceOperatingSystem.macos:
939
          await flutter('build', options: <String>[
940
            if (deviceOperatingSystem == DeviceOperatingSystem.ios) 'ios' else 'macos',
941 942
             '-v',
            '--profile',
943
            '--target=$target',
944
            if (deviceOperatingSystem == DeviceOperatingSystem.ios) '--no-publish-port',
945
          ]);
946 947
          final String buildRoot = path.join(testDirectory, 'build');
          applicationBinaryPath = _findDarwinAppInBuildDirectory(buildRoot);
948
        case DeviceOperatingSystem.windows:
949 950 951 952 953 954 955 956 957 958 959
          await flutter('build', options: <String>[
            'windows',
            '-v',
            '--profile',
            '--target=$target',
          ]);
          final String basename = path.basename(testDirectory);
          applicationBinaryPath = path.join(
            testDirectory,
            'build',
            'windows',
960
            'x64',
961 962 963 964
            'runner',
            'Profile',
            '$basename.exe'
          );
965 966
      }

967 968
      const int maxFailures = 3;
      int currentFailures = 0;
969
      for (int i = 0; i < iterations; i += 1) {
970 971 972 973 974 975 976 977 978
        // 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',
          );
        });
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
        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,
        );
999
        timer.cancel();
1000 1001
        if (result == 0) {
          final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
1002
            file('${_testOutputDirectory(testDirectory)}/start_up_info.json').readAsStringSync(),
1003 1004 1005 1006
          ) as Map<String, dynamic>;
          results.add(data);
        } else {
          currentFailures += 1;
1007 1008 1009 1010
          await _flutterScreenshot(
            device.deviceId,
            'screenshot_startup_failure_$currentFailures.png',
          );
1011 1012 1013 1014 1015
          i -= 1;
          if (currentFailures == maxFailures) {
            return TaskResult.failure('Application failed to start $maxFailures times');
          }
        }
1016

1017
        await device.uninstallApp();
1018 1019 1020
      }

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

1022
      if (!reportMetrics) {
1023
        return TaskResult.success(averageResults);
1024
      }
1025

1026
      return TaskResult.success(averageResults, benchmarkScoreKeys: <String>[
1027
        'timeToFirstFrameMicros',
1028
        'timeToFirstFrameRasterizedMicros',
1029 1030 1031
      ]);
    });
  }
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

  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,
      );
    }
  }
1049 1050
}

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/// 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');
1062
      String? applicationBinaryPath;
1063 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 1093
      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',
          ]);
1094
          applicationBinaryPath = _findDarwinAppInBuildDirectory('$testDirectory/build/ios/iphoneos');
1095
        case DeviceOperatingSystem.fake:
1096
        case DeviceOperatingSystem.fuchsia:
1097
        case DeviceOperatingSystem.linux:
1098 1099
        case DeviceOperatingSystem.macos:
        case DeviceOperatingSystem.windows:
1100 1101 1102
          break;
      }

1103
      final Process process = await startFlutter(
1104
        'run',
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        options: <String>[
          '--no-android-gradle-daemon',
          '--no-publish-port',
          '--verbose',
          '--profile',
          '-d',
          device.deviceId,
          if (applicationBinaryPath != null)
            '--use-application-binary=$applicationBinaryPath',
       ],
      );
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
      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;
      }

1139
      await device.uninstallApp();
1140

1141
      if (sawLine) {
1142
        return TaskResult.success(null, benchmarkScoreKeys: <String>[]);
1143
      }
1144 1145 1146 1147 1148
      return TaskResult.failure('Did not see line "The Flutter DevTools debugger and profiler" in output');
    });
  }
}

1149 1150 1151 1152 1153
/// 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);

1154 1155 1156
/// Measures application runtime performance, specifically per-frame
/// performance.
class PerfTest {
1157
  const PerfTest(
1158 1159 1160
    this.testDirectory,
    this.testTarget,
    this.timelineFileName, {
1161
    this.measureCpuGpu = true,
1162
    this.measureMemory = true,
1163
    this.measureTotalGCTime = true,
1164
    this.saveTraceFile = false,
1165
    this.testDriver,
1166 1167
    this.needsFullTimeline = true,
    this.benchmarkScoreKeys,
1168
    this.dartDefine = '',
1169
    String? resultFilename,
1170 1171
    this.device,
    this.flutterDriveCallback,
1172
    this.timeoutSeconds,
1173
    this.enableImpeller,
1174
    this.forceOpenGLES,
1175
    this.disablePartialRepaint = false,
1176 1177 1178 1179 1180
  }): _resultFilename = resultFilename;

  const PerfTest.e2e(
    this.testDirectory,
    this.testTarget, {
1181 1182
    this.measureCpuGpu = false,
    this.measureMemory = false,
1183
    this.measureTotalGCTime = false,
1184 1185 1186 1187 1188
    this.testDriver =  'test_driver/e2e_test.dart',
    this.needsFullTimeline = false,
    this.benchmarkScoreKeys = _kCommonScoreKeys,
    this.dartDefine = '',
    String resultFilename = 'e2e_perf_summary',
1189 1190
    this.device,
    this.flutterDriveCallback,
1191
    this.timeoutSeconds,
1192
    this.enableImpeller,
1193
    this.forceOpenGLES,
1194
    this.disablePartialRepaint = false,
1195
  }) : saveTraceFile = false, timelineFileName = null, _resultFilename = resultFilename;
1196 1197

  /// The directory where the app under test is defined.
1198
  final String testDirectory;
1199
  /// The main entry-point file of the application, as run on the device.
1200
  final String testTarget;
1201
  // The prefix name of the filename such as `<timelineFileName>.timeline_summary.json`.
1202
  final String? timelineFileName;
1203
  String get traceFilename => '$timelineFileName.timeline';
1204
  String get resultFilename => _resultFilename ?? '$timelineFileName.timeline_summary';
1205
  final String? _resultFilename;
1206
  /// The test file to run on the host.
1207
  final String? testDriver;
1208
  /// Whether to collect CPU and GPU metrics.
1209
  final bool measureCpuGpu;
1210 1211
  /// Whether to collect memory metrics.
  final bool measureMemory;
1212 1213
  /// Whether to summarize total GC time on the UI thread from the timeline.
  final bool measureTotalGCTime;
1214 1215
  /// Whether to collect full timeline, meaning if `--trace-startup` flag is needed.
  final bool needsFullTimeline;
1216 1217
  /// Whether to save the trace timeline file `*.timeline.json`.
  final bool saveTraceFile;
1218 1219 1220 1221 1222 1223 1224 1225 1226
  /// 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;
1227

1228
  /// Whether the perf test should enable Impeller.
1229
  final bool? enableImpeller;
1230

1231 1232 1233
  /// Whether the perf test force Impeller's OpenGLES backend.
  final bool? forceOpenGLES;

1234 1235 1236
  /// Whether partial repaint functionality should be disabled (iOS only).
  final bool disablePartialRepaint;

1237 1238 1239
  /// Number of seconds to time out the test after, allowing debug callbacks to run.
  final int? timeoutSeconds;

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
  /// 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',
1256 1257
  ///   if (measureCpuGpu) 'average_cpu_usage',
  ///   if (measureCpuGpu) 'average_gpu_usage',
1258 1259
  /// ]
  /// ```
1260
  final List<String>? benchmarkScoreKeys;
1261

1262 1263 1264
  /// Additional flags for `--dart-define` to control the test
  final String dartDefine;

1265
  Future<TaskResult> run() {
1266 1267 1268 1269 1270
    return internalRun();
  }

  @protected
  Future<TaskResult> internalRun({
1271
      String? existingApp,
1272
  }) {
1273
    return inDirectory<TaskResult>(testDirectory, () async {
1274 1275 1276 1277 1278 1279 1280 1281
      late Device selectedDevice;
      if (device != null) {
        selectedDevice = device!;
      } else {
        selectedDevice = await devices.workingDevice;
      }
      await selectedDevice.unlock();
      final String deviceId = selectedDevice.deviceId;
1282
      final String? localEngine = localEngineFromEnv;
1283
      final String? localEngineHost = localEngineHostFromEnv;
1284
      final String? localEngineSrcPath = localEngineSrcPathFromEnv;
1285

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
      bool changedPlist = false;
      bool changedManifest = false;

      Future<void> resetManifest() async {
        if (!changedManifest) {
          return;
        }
        try {
          await _resetManifest(testDirectory);
        } catch (err) {
          print('Caught exception while trying to reset AndroidManifest: $err');
        }
      }

      Future<void> resetPlist() async {
        if (!changedPlist) {
          return;
        }
        try {
          await _resetPlist(testDirectory);
        } catch (err) {
           print('Caught exception while trying to reset Info.plist: $err');
        }
1309 1310 1311
      }

      try {
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        if (forceOpenGLES ?? false) {
          assert(enableImpeller!);
          changedManifest = true;
          _addOpenGLESToManifest(testDirectory);
        }
        if (disablePartialRepaint) {
          changedPlist = true;
          _disablePartialRepaint(testDirectory);
        }

1322 1323
        final List<String> options = <String>[
          if (localEngine != null) ...<String>['--local-engine', localEngine],
1324 1325 1326 1327
          if (localEngineHost != null) ...<String>[
            '--local-engine-host',
            localEngineHost
          ],
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
          if (localEngineSrcPath != null) ...<String>[
            '--local-engine-src-path',
            localEngineSrcPath
          ],
          '--no-dds',
          '--no-android-gradle-daemon',
          '-v',
          '--verbose-system-logs',
          '--profile',
          if (timeoutSeconds != null) ...<String>[
1338 1339 1340
            '--timeout',
            timeoutSeconds.toString(),
          ],
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
          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 {
1362 1363
        await resetManifest();
        await resetPlist();
1364
      }
1365

1366
      final Map<String, dynamic> data = json.decode(
Dan Field's avatar
Dan Field committed
1367
        file('${_testOutputDirectory(testDirectory)}/$resultFilename.json').readAsStringSync(),
1368
      ) as Map<String, dynamic>;
1369

1370
      if (data['frame_count'] as int < 5) {
1371
        return TaskResult.failure(
1372 1373 1374 1375 1376
          'Timeline contains too few frames: ${data['frame_count']}. Possibly '
          'trace events are not being captured.',
        );
      }

1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
      final bool recordGPU;
      switch (deviceOperatingSystem) {
        case DeviceOperatingSystem.ios:
          recordGPU = true;
        case DeviceOperatingSystem.android:
        case DeviceOperatingSystem.androidArm:
        case DeviceOperatingSystem.androidArm64:
          recordGPU = enableImpeller ?? false;
        case DeviceOperatingSystem.fake:
        case DeviceOperatingSystem.fuchsia:
        case DeviceOperatingSystem.linux:
        case DeviceOperatingSystem.macos:
        case DeviceOperatingSystem.windows:
          recordGPU = false;
      }

1393 1394 1395
      // TODO(liyuqian): Remove isAndroid restriction once
      // https://github.com/flutter/flutter/issues/61567 is fixed.
      final bool isAndroid = deviceOperatingSystem == DeviceOperatingSystem.android;
1396 1397
      return TaskResult.success(
        data,
1398 1399
        detailFiles: <String>[
          if (saveTraceFile)
Dan Field's avatar
Dan Field committed
1400
            '${_testOutputDirectory(testDirectory)}/$traceFilename.json',
1401
        ],
1402
        benchmarkScoreKeys: benchmarkScoreKeys ?? <String>[
1403
          ..._kCommonScoreKeys,
1404 1405 1406
          'average_vsync_transitions_missed',
          '90th_percentile_vsync_transitions_missed',
          '99th_percentile_vsync_transitions_missed',
1407 1408 1409
          'average_frame_request_pending_latency',
          '90th_percentile_frame_request_pending_latency',
          '99th_percentile_frame_request_pending_latency',
1410
          if (measureCpuGpu && !isAndroid) ...<String>[
1411 1412 1413
            // 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',
1414 1415
          ],
          if (measureMemory && !isAndroid) ...<String>[
1416 1417
            // See https://github.com/flutter/flutter/issues/68888
            if (data['average_memory_usage'] != null) 'average_memory_usage',
1418 1419
            if (data['90th_percentile_memory_usage'] != null) '90th_percentile_memory_usage',
            if (data['99th_percentile_memory_usage'] != null) '99th_percentile_memory_usage',
1420
          ],
1421
          if (measureTotalGCTime) 'total_ui_gc_time',
1422 1423 1424 1425 1426 1427
          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',
1428 1429 1430 1431 1432 1433
          if (recordGPU) ...<String>[
            if (data['average_gpu_frame_time'] != null) 'average_gpu_frame_time',
            if (data['90th_percentile_gpu_frame_time'] != null) '90th_percentile_gpu_frame_time',
            if (data['99th_percentile_gpu_frame_time'] != null) '99th_percentile_gpu_frame_time',
            if (data['worst_gpu_frame_time'] != null) 'worst_gpu_frame_time',
          ]
1434 1435
        ],
      );
1436 1437 1438 1439
    });
  }
}

1440 1441 1442 1443 1444 1445 1446 1447 1448
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',
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  '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',
1465
  'old_gen_gc_count',
1466
];
1467

1468 1469 1470 1471 1472 1473 1474
/// 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>{};
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491

    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 {
1492
      await flutter('create', options: <String>['--template=app', sampleAppName]);
1493
    });
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

    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].
1507 1508 1509 1510 1511
  static Future<Map<String, int>> runSingleBuildTest({
    required String directory,
    required String metric,
    bool measureBuildTime = false,
  }) {
1512 1513 1514
    return inDirectory<Map<String, int>>(directory, () async {
      final Map<String, int> metrics = <String, int>{};

1515
      await flutter('clean');
1516
      await flutter('packages', options: <String>['get']);
1517
      final Stopwatch? watch = measureBuildTime ? Stopwatch() : null;
1518
      watch?.start();
1519 1520 1521 1522 1523
      await evalFlutter('build', options: <String>[
        'web',
        '-v',
        '--release',
        '--no-pub',
1524
        '--no-web-resources-cdn',
1525
      ]);
1526
      watch?.stop();
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
      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,
      ));
1538

1539
      if (measureBuildTime) {
1540
        metrics['${metric}_dart2js_millis'] = watch!.elapsedMilliseconds;
1541
      }
1542

1543
      return metrics;
1544 1545 1546
    });
  }

1547 1548 1549 1550 1551 1552 1553 1554 1555
  /// 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';
1556 1557
    final Map<String, int> sizeMetrics = <String, int>{};

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    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();
      }
1572

1573 1574 1575
      for (final MapEntry<String, String> entry in directories.entries) {
        final String key = entry.key;
        final String dirPath = entry.value;
1576

1577 1578 1579 1580 1581 1582 1583 1584
        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();
1585

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
        // 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;
1598 1599 1600
  }
}

1601
/// Measures how long it takes to compile a Flutter app and how big the compiled
1602
/// code is.
1603
class CompileTest {
1604
  const CompileTest(this.testDirectory, { this.reportPackageContentSizes = false });
1605 1606

  final String testDirectory;
1607
  final bool reportPackageContentSizes;
1608

1609
  Future<TaskResult> run() async {
1610
    return inDirectory<TaskResult>(testDirectory, () async {
1611
      await flutter('packages', options: <String>['get']);
1612

1613 1614 1615 1616 1617
      // "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(
1618
        clean: true,
1619 1620 1621 1622 1623 1624
        deleteGradleCache: true,
        metricKey: 'debug_initial_compile_millis',
      );
      final Map<String, dynamic> compileFullDebug = await _compileDebug(
        clean: true,
        deleteGradleCache: false,
1625 1626 1627 1628 1629
        metricKey: 'debug_full_compile_millis',
      );
      // Build again without cleaning, should be faster.
      final Map<String, dynamic> compileSecondDebug = await _compileDebug(
        clean: false,
1630
        deleteGradleCache: false,
1631 1632 1633
        metricKey: 'debug_second_compile_millis',
      );

1634
      final Map<String, dynamic> metrics = <String, dynamic>{
1635 1636 1637 1638
        ...compileInitialRelease,
        ...compileFullRelease,
        ...compileInitialDebug,
        ...compileFullDebug,
1639
        ...compileSecondDebug,
1640
      };
1641

1642 1643 1644 1645 1646 1647 1648 1649
      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,
1650
          deleteGradleCache: false,
1651 1652 1653 1654 1655 1656 1657
          metricKey: 'debug_compile_after_edit_millis',
        );
        metrics.addAll(compileAfterEditDebug);
        // Revert the changes
        mainDart.writeAsBytesSync(bytes, flush: true);
      }

1658
      return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
1659 1660
    });
  }
1661

1662
  Future<Map<String, dynamic>> _compileApp({required bool deleteGradleCache}) async {
1663
    await flutter('clean');
1664 1665 1666 1667
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1668
    final Stopwatch watch = Stopwatch();
1669 1670
    int releaseSizeInBytes;
    final List<String> options = <String>['--release'];
1671 1672
    final Map<String, dynamic> metrics = <String, dynamic>{};

Ian Hickson's avatar
Ian Hickson committed
1673 1674
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
      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);
1687 1688
        options.add('--tree-shake-icons');
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1689
        watch.start();
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
        await flutter(
          'build',
          options: options,
          environment: <String, String> {
            // iOS 12.1 and lower did not have Swift ABI compatibility so Swift apps embedded the Swift runtime.
            // https://developer.apple.com/documentation/xcode-release-notes/swift-5-release-notes-for-xcode-10_2#App-Thinning
            // The gallery pulls in Swift plugins. Set lowest version to 12.2 to avoid benchmark noise.
            // This should be removed when when Flutter's minimum supported version is >12.2.
            'FLUTTER_XCODE_IPHONEOS_DEPLOYMENT_TARGET': '12.2',
          },
        );
Ian Hickson's avatar
Ian Hickson committed
1701
        watch.stop();
1702 1703 1704 1705
        final Directory buildDirectory = dir(path.join(
          cwd,
          'build',
        ));
1706
        final String? appPath =
1707
            _findDarwinAppInBuildDirectory(buildDirectory.path);
1708
        if (appPath == null) {
1709
          throw 'Failed to find app bundle in ${buildDirectory.path}';
1710
        }
1711 1712 1713 1714
        // 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();
1715
        if (reportPackageContentSizes) {
1716
          final Map<String, Object> sizeMetrics = await getSizesFromDarwinApp(
1717 1718
            appPath: appPath,
            operatingSystem: deviceOperatingSystem,
1719 1720
          );
          metrics.addAll(sizeMetrics);
1721
        }
Ian Hickson's avatar
Ian Hickson committed
1722
      case DeviceOperatingSystem.android:
1723
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1724
        options.insert(0, 'apk');
1725
        options.add('--target-platform=android-arm');
1726
        options.add('--tree-shake-icons');
1727
        options.add('--split-debug-info=infos/');
Ian Hickson's avatar
Ian Hickson committed
1728 1729 1730
        watch.start();
        await flutter('build', options: options);
        watch.stop();
1731 1732
        final String apkPath = '$cwd/build/app/outputs/flutter-apk/app-release.apk';
        final File apk = file(apkPath);
1733
        releaseSizeInBytes = apk.lengthSync();
1734
        if (reportPackageContentSizes) {
1735
          metrics.addAll(await getSizesFromApk(apkPath));
1736
        }
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
      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();
1748
        if (reportPackageContentSizes) {
1749
          metrics.addAll(await getSizesFromApk(apkPath));
1750
        }
1751 1752
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1753 1754
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
1755 1756
      case DeviceOperatingSystem.linux:
        throw Exception('Unsupported option for Linux devices');
1757
      case DeviceOperatingSystem.windows:
1758 1759 1760 1761 1762 1763 1764
        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();
1765 1766
        final String basename = path.basename(cwd);
        final String exePath = path.join(
1767 1768 1769
          cwd,
          'build',
          'windows',
1770
          'x64',
1771 1772
          'runner',
          'release',
1773 1774
          '$basename.exe');
        final File exe = file(exePath);
1775
        // On Windows, we do not produce a single installation package file,
1776 1777 1778
        // 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();
1779
    }
1780

1781
    metrics.addAll(<String, dynamic>{
1782
      'release_${deleteGradleCache ? 'initial' : 'full'}_compile_millis': watch.elapsedMilliseconds,
1783
      'release_size_bytes': releaseSizeInBytes,
1784 1785 1786
    });

    return metrics;
1787 1788
  }

1789 1790
  Future<Map<String, dynamic>> _compileDebug({
    required bool deleteGradleCache,
1791 1792
    required bool clean,
    required String metricKey,
1793 1794 1795 1796
  }) async {
    if (clean) {
      await flutter('clean');
    }
1797 1798 1799 1800
    if (deleteGradleCache) {
      final Directory gradleCacheDir = Directory('$testDirectory/android/.gradle');
      rmTree(gradleCacheDir);
    }
1801
    final Stopwatch watch = Stopwatch();
Ian Hickson's avatar
Ian Hickson committed
1802 1803 1804 1805 1806
    final List<String> options = <String>['--debug'];
    switch (deviceOperatingSystem) {
      case DeviceOperatingSystem.ios:
        options.insert(0, 'ios');
      case DeviceOperatingSystem.android:
1807
      case DeviceOperatingSystem.androidArm:
Ian Hickson's avatar
Ian Hickson committed
1808
        options.insert(0, 'apk');
1809
        options.add('--target-platform=android-arm');
1810 1811 1812
      case DeviceOperatingSystem.androidArm64:
        options.insert(0, 'apk');
        options.add('--target-platform=android-arm64');
1813 1814
      case DeviceOperatingSystem.fake:
        throw Exception('Unsupported option for fake devices');
1815 1816
      case DeviceOperatingSystem.fuchsia:
        throw Exception('Unsupported option for Fuchsia devices');
1817 1818
      case DeviceOperatingSystem.linux:
        throw Exception('Unsupported option for Linux devices');
1819
      case DeviceOperatingSystem.macos:
1820 1821
        unawaited(stderr.flush());
        options.insert(0, 'macos');
1822
      case DeviceOperatingSystem.windows:
1823 1824
        unawaited(stderr.flush());
        options.insert(0, 'windows');
1825
    }
Ian Hickson's avatar
Ian Hickson committed
1826 1827 1828
    watch.start();
    await flutter('build', options: options);
    watch.stop();
1829 1830

    return <String, dynamic>{
1831
      metricKey: watch.elapsedMilliseconds,
1832 1833 1834
    };
  }

1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
  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:
1868
      case DeviceOperatingSystem.linux:
1869 1870 1871
      case DeviceOperatingSystem.windows:
        throw Exception('Called ${CompileTest.getSizesFromDarwinApp} with $operatingSystem.');
    }
1872

1873 1874 1875 1876 1877
    final File appFramework = File(path.join(
      frameworkDirectory,
      'App.framework',
      'App',
    ));
1878

1879
    return <String, Object>{
1880 1881 1882 1883 1884
      'app_framework_uncompressed_bytes': await appFramework.length(),
      'flutter_framework_uncompressed_bytes': await flutterFramework.length(),
    };
  }

1885 1886 1887 1888 1889 1890 1891
  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++) {
1892
      final _UnzipListEntry entry = _UnzipListEntry.fromLine(lines[i]);
1893 1894 1895
      fileToMetadata[entry.path] = entry;
    }

1896 1897 1898
    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']!;
1899 1900 1901 1902

    return <String, dynamic>{
      'libflutter_uncompressed_bytes': libflutter.uncompressedSize,
      'libflutter_compressed_bytes': libflutter.compressedSize,
1903 1904
      'libapp_uncompressed_bytes': libapp.uncompressedSize,
      'libapp_compressed_bytes': libapp.compressedSize,
1905 1906
      'license_uncompressed_bytes': license.uncompressedSize,
      'license_compressed_bytes': license.compressedSize,
1907 1908
    };
  }
1909
}
1910

1911
/// Measure application memory usage.
1912
class MemoryTest {
1913 1914 1915 1916 1917 1918 1919 1920
  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`.
1921 1922 1923
  Future<void>? get receivedNextMessage => _receivedNextMessage?.future;
  Completer<void>? _receivedNextMessage;
  String? _nextMessage;
1924 1925 1926 1927 1928

  /// 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;
1929
    _receivedNextMessage = Completer<void>();
1930
  }
1931

1932
  int get iterationCount => 10;
1933

1934 1935
  Device? get device => _device;
  Device? _device;
1936

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

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

1946
      final StreamSubscription<String> adb = device!.logcat.listen(
1947
        (String data) {
1948
          if (data.contains('==== MEMORY BENCHMARK ==== $_nextMessage ====')) {
1949
            _receivedNextMessage?.complete();
1950
          }
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
        },
      );

      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...');
1963
        await device!.stop(package);
1964
        await Future<void>.delayed(const Duration(milliseconds: 10));
1965
      }
1966

1967
      await adb.cancel();
1968
      await device!.uninstallApp();
1969

1970 1971 1972
      final ListStatistics startMemoryStatistics = ListStatistics(_startMemory);
      final ListStatistics endMemoryStatistics = ListStatistics(_endMemory);
      final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory);
1973

1974 1975 1976 1977 1978
      final Map<String, dynamic> memoryUsage = <String, dynamic>{
        ...startMemoryStatistics.asMap('start'),
        ...endMemoryStatistics.asMap('end'),
        ...diffMemoryStatistics.asMap('diff'),
      };
1979

1980 1981 1982 1983 1984
      _device = null;
      _startMemory.clear();
      _endMemory.clear();
      _diffMemory.clear();

1985
      return TaskResult.success(memoryUsage, benchmarkScoreKeys: memoryUsage.keys.toList());
1986 1987
    });
  }
1988

1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
  /// 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',
1999
      '-d', device!.deviceId,
2000 2001 2002 2003 2004
      test,
    ]);
    print('awaiting "ready" message...');
    await receivedNextMessage;
  }
2005

2006
  /// To change the behavior of the test, override this.
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
  ///
  /// 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...');
2018
    await device!.tap(100, 100);
2019 2020 2021 2022 2023
    print('awaiting "done" message...');
    await receivedNextMessage;

    await recordEnd();
  }
2024

2025 2026 2027
  final List<int> _startMemory = <int>[];
  final List<int> _endMemory = <int>[];
  final List<int> _diffMemory = <int>[];
2028

2029
  Map<String, dynamic>? _startMemoryUsage;
2030

2031 2032 2033 2034
  @protected
  Future<void> recordStart() async {
    assert(_startMemoryUsage == null);
    print('snapshotting memory usage...');
2035
    _startMemoryUsage = await device!.getMemoryStats(package);
2036
  }
2037

2038 2039 2040 2041
  @protected
  Future<void> recordEnd() async {
    assert(_startMemoryUsage != null);
    print('snapshotting memory usage...');
2042 2043
    final Map<String, dynamic> endMemoryUsage = await device!.getMemoryStats(package);
    _startMemory.add(_startMemoryUsage!['total_kb'] as int);
2044
    _endMemory.add(endMemoryUsage['total_kb'] as int);
2045
    _diffMemory.add((endMemoryUsage['total_kb'] as int) - (_startMemoryUsage!['total_kb'] as int));
2046 2047
  }
}
2048

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
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',
2065 2066 2067
          '--profile-memory', _kJsonFileName,
          '--no-publish-port',
          '-v',
2068 2069 2070 2071 2072 2073 2074
          driverTest,
        ],
      );

      final Map<String, dynamic> data = json.decode(
        file('$project/$_kJsonFileName').readAsStringSync(),
      ) as Map<String, dynamic>;
2075
      final List<dynamic> samples = (data['samples'] as Map<String, dynamic>)['data'] as List<dynamic>;
2076 2077
      int maxRss = 0;
      int maxAdbTotal = 0;
2078
      for (final Map<String, dynamic> sample in samples.cast<Map<String, dynamic>>()) {
2079 2080 2081
        if (sample['rss'] != null) {
          maxRss = math.max(maxRss, sample['rss'] as int);
        }
2082
        if (sample['adb_memoryInfo'] != null) {
2083
          maxAdbTotal = math.max(maxAdbTotal, (sample['adb_memoryInfo'] as Map<String, dynamic>)['Total'] as int);
2084 2085
        }
      }
2086

2087
      return TaskResult.success(
2088 2089
        <String, dynamic>{'maxRss': maxRss, 'maxAdbTotal': maxAdbTotal},
        benchmarkScoreKeys: <String>['maxRss', 'maxAdbTotal'],
2090 2091 2092 2093
      );
    });
  }

2094
  late Device _device;
2095 2096 2097 2098

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

2099 2100 2101 2102 2103
enum ReportedDurationTestFlavor {
  debug, profile, release
}

String _reportedDurationTestToString(ReportedDurationTestFlavor flavor) {
2104 2105 2106 2107 2108
  return switch (flavor) {
    ReportedDurationTestFlavor.debug   => 'debug',
    ReportedDurationTestFlavor.profile => 'profile',
    ReportedDurationTestFlavor.release => 'release',
  };
2109 2110
}

2111
class ReportedDurationTest {
2112
  ReportedDurationTest(this.flavor, this.project, this.test, this.package, this.durationPattern);
2113

2114
  final ReportedDurationTestFlavor flavor;
2115 2116 2117 2118 2119 2120 2121 2122 2123
  final String project;
  final String test;
  final String package;
  final RegExp durationPattern;

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

  int get iterationCount => 10;

2124 2125
  Device? get device => _device;
  Device? _device;
2126 2127 2128 2129 2130 2131 2132

  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;
2133
      await device!.unlock();
2134 2135
      await flutter('packages', options: <String>['get']);

2136
      final StreamSubscription<String> adb = device!.logcat.listen(
2137
        (String data) {
2138
          if (durationPattern.hasMatch(data)) {
2139
            durationCompleter.complete(int.parse(durationPattern.firstMatch(data)!.group(1)!));
2140
          }
2141 2142 2143 2144 2145
        },
      );
      print('launching $project$test on device...');
      await flutter('run', options: <String>[
        '--verbose',
2146
        '--no-publish-port',
2147
        '--no-fast-start',
2148
        '--${_reportedDurationTestToString(flavor)}',
2149
        '--no-resident',
2150
        '-d', device!.deviceId,
2151 2152 2153 2154 2155
        test,
      ]);

      final int duration = await durationCompleter.future;
      print('terminating...');
2156
      await device!.stop(package);
2157 2158 2159 2160 2161
      await adb.cancel();

      _device = null;

      final Map<String, dynamic> reportedDuration = <String, dynamic>{
2162
        'duration': duration,
2163 2164 2165 2166 2167 2168 2169 2170
      };
      _device = null;

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

2171 2172 2173 2174
/// Holds simple statistics of an odd-lengthed list of integers.
class ListStatistics {
  factory ListStatistics(Iterable<int> data) {
    assert(data.isNotEmpty);
2175
    assert(data.length.isOdd);
2176
    final List<int> sortedData = data.toList()..sort();
2177
    return ListStatistics._(
2178 2179 2180 2181 2182
      sortedData.first,
      sortedData.last,
      sortedData[(sortedData.length - 1) ~/ 2],
    );
  }
2183

2184
  const ListStatistics._(this.min, this.max, this.median);
2185

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
  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,
    };
2196 2197
  }
}
2198 2199 2200

class _UnzipListEntry {
  factory _UnzipListEntry.fromLine(String line) {
2201
    final List<String> data = line.trim().split(RegExp(r'\s+'));
2202
    assert(data.length == 8);
2203
    return _UnzipListEntry._(
2204 2205 2206 2207 2208 2209 2210
      uncompressedSize:  int.parse(data[0]),
      compressedSize: int.parse(data[2]),
      path: data[7],
    );
  }

  _UnzipListEntry._({
2211 2212 2213
    required this.uncompressedSize,
    required this.compressedSize,
    required this.path,
2214
  }) : assert(compressedSize <= uncompressedSize);
2215 2216 2217 2218 2219

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

2221
/// Wait for up to 1 hour for the file to appear.
2222
Future<File> waitForFile(String path) async {
2223
  for (int i = 0; i < 180; i += 1) {
2224 2225 2226 2227 2228 2229 2230
    final File file = File(path);
    print('looking for ${file.path}');
    if (file.existsSync()) {
      return file;
    }
    await Future<void>.delayed(const Duration(seconds: 20));
  }
2231
  throw StateError('Did not find vmservice out file after 1 hour');
2232 2233
}

2234 2235 2236
String? _findDarwinAppInBuildDirectory(String searchDirectory) {
  for (final FileSystemEntity entity in Directory(searchDirectory)
    .listSync(recursive: true)) {
2237 2238 2239 2240 2241 2242
    if (entity.path.endsWith('.app')) {
      return entity.path;
    }
  }
  return null;
}