platform/lib/src/stats/stats.dart

53 lines
863 B
Dart
Raw Normal View History

2017-10-28 08:50:16 +00:00
/// Computes averages progressively.
import 'dart:async';
class Stats {
final String name;
int _total = 0, _count = 0;
double _average = 0.0;
Stats(this.name);
double get average => _average ?? (_total / _count);
2017-11-18 17:42:31 +00:00
int get iterations => _count;
int get sum => _total;
2017-10-28 08:50:16 +00:00
void log() {
print('$name: $average avg.');
}
void add(int value) {
_average = null;
_total += value;
_count++;
}
FutureOr<T> run<T>(FutureOr<T> f()) {
var sw = new Stopwatch();
//print('--- $name START');
sw.start();
void whenDone() {
sw.stop();
var ms = sw.elapsedMilliseconds;
add(ms);
2017-11-18 17:42:31 +00:00
//print('--- $name DONE after ${ms}ms');
2017-10-28 08:50:16 +00:00
}
var r = f();
if (r is Future) {
return (r as Future).then((x) {
whenDone();
return x;
});
}
whenDone();
return r;
}
}