首页 > 解决方案 > 如何准确统计 dart 代码的运行速度

问题描述

我写了一个测试方法,尝试统计代码运行速度,下面是我的测试代码:

test('speed',  (){
    int count = 10000;

    int t1 = DateTime.now().microsecondsSinceEpoch;
    for (int i = 0; i < count; i++) {

    }
    print("first for loop spend ${DateTime.now().microsecondsSinceEpoch - t1}");

    int t2 = DateTime.now().microsecondsSinceEpoch;
    for (int j = 0; j < count; j++) {

    }
    print("second for loop spend ${DateTime.now().microsecondsSinceEpoch - t2}");
});

我运行这个测试方法,控制台打印:

第一个 for 循环花费 106

第二个for循环花费440

我不明白为什么第二个 for 循环比第一个循环花费更多时间,他们做同样的事情。

准确统计 dart 代码运行速度的最佳方法是什么。

Dart SDK 版本 2.5.2 在 MacOS 10.15.1 上运行

标签: flutterdart

解决方案


我认为你最好使用秒表之类的东西来测量经过的时间。

test('speed',  (){
    int count = 10000;

    final stopwatch = Stopwatch()..start();
    for (int i = 0; i < count; i++) {

    }
    stopwatch.stop();
    print("first for loop spend ${stopwatch.elapsedMilliseconds}");

    final stopwatch1 = Stopwatch()..start();
    for (int j = 0; j < count; j++) {

    }
    stopwatch1.stop();
    print("second for loop spend ${stopwatch1.elapsedMilliseconds}");
  });

推荐阅读