flutter - 如何准确统计 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 上运行
解决方案
我认为你最好使用秒表之类的东西来测量经过的时间。
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}");
});
推荐阅读
- node.js - 为什么nodejs文件系统先读取控制台再读取文件
- arrays - 为什么在 C 语言循环中,访问数组元素比访问变量慢很多?
- php - 观看任务并再次获取任务 - Vuejs
- azure - 使用 Azure VM 进行软件开发和测试(而不是托管)
- node.js - Safari 推送通知,识别点击操作按钮
- c# - 预配 Azure 应用程序网关实例时如何引用子资源
- javascript - Nextjs,如何从 _app.tsx 重定向
- google-chrome-devtools - 有没有办法将 chrome profiler 与控制台日志或在时间轴上放置标记相关联?
- php - Laravel selectRaw中按月分组的SQL
- ibm-mq - 如何在 CachingConnectionFactory 中查找会话缓存耗尽