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

5
import 'package:flutter/material.dart';
6
import 'package:flutter_test/flutter_test.dart';
7 8 9
import 'package:stocks/main.dart' as stocks;
import 'package:stocks/stock_data.dart' as stock_data;

10 11
import '../common.dart';

12
const Duration kBenchmarkTime = Duration(seconds: 15);
13

14
Future<void> main() async {
15
  assert(false, "Don't run benchmarks in checked mode! Use 'flutter run --release'.");
16
  stock_data.StockData.actuallyFetchData = false;
17

18 19
  // We control the framePolicy below to prevent us from scheduling frames in
  // the engine, so that the engine does not interfere with our timings.
20
  final LiveTestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized() as LiveTestWidgetsFlutterBinding;
21

22
  final Stopwatch watch = Stopwatch();
23
  int iterations = 0;
24
  final List<double> values = <double>[];
25 26 27 28 29

  await benchmarkWidgets((WidgetTester tester) async {
    stocks.main();
    await tester.pump(); // Start startup animation
    await tester.pump(const Duration(seconds: 1)); // Complete startup animation
30
    await tester.tapAt(const Offset(20.0, 40.0)); // Open drawer
31 32 33
    await tester.pump(); // Start drawer animation
    await tester.pump(const Duration(seconds: 1)); // Complete drawer animation

34
    final Element appState = tester.element(find.byType(stocks.StocksApp));
35
    binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmark;
36

37 38 39 40
    Duration elapsed = Duration.zero;
    while (elapsed < kBenchmarkTime) {
      watch.reset();
      watch.start();
41
      appState.markNeedsBuild();
42 43 44 45
      // We don't use tester.pump() because we're trying to drive it in an
      // artificially high load to find out how much CPU each frame takes.
      // This differs from normal benchmarks which might look at how many
      // frames are missed, etc.
46 47
      // We use Timer.run to ensure there's a microtask flush in between
      // the two calls below.
48
      await tester.pumpBenchmark(Duration(milliseconds: iterations * 16));
49
      watch.stop();
50
      iterations += 1;
51 52
      elapsed += Duration(microseconds: watch.elapsedMicroseconds);
      values.add(watch.elapsedMicroseconds.toDouble());
53 54 55
    }
  });

56
  final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
57
  printer.addResultStatistics(
58
    description: 'Stock build',
59
    values: values,
60 61 62 63
    unit: 'µs per iteration',
    name: 'stock_build_iteration',
  );
  printer.printToStdout();
64
}