Files
TelemetryMonitor/lib/session/pps_counter.dart
2026-04-21 14:40:09 -03:00

34 lines
926 B
Dart

import 'dart:collection';
/// Sliding-window packets-per-second counter.
///
/// Measures wall-clock arrival rate, which intentionally differs from the
/// timestamp_us field in the packet (server time). Network jitter makes the
/// two diverge.
class PpsCounter {
PpsCounter({this.window = const Duration(seconds: 1)});
final Duration window;
final Queue<DateTime> _arrivals = Queue();
void recordArrival([DateTime? now]) {
_arrivals.add(now ?? DateTime.now());
_evictOld(now);
}
/// Current PPS measurement.
double current([DateTime? now]) {
_evictOld(now);
final secs = window.inMilliseconds / 1000.0;
return _arrivals.length / secs;
}
void reset() => _arrivals.clear();
void _evictOld(DateTime? now) {
final cutoff = (now ?? DateTime.now()).subtract(window);
while (_arrivals.isNotEmpty && _arrivals.first.isBefore(cutoff)) {
_arrivals.removeFirst();
}
}
}