Downsample metric samples by averaging within fixed time windows. Given samples sorted by timestamp and a window size (in ms), returns one (timestamp, avg_value) per window. The timestamp is the start of the window.
(samples: &[(i64, f64)], window_ms: i64)
| 387 | /// one (timestamp, avg_value) per window. The timestamp is the start |
| 388 | /// of the window. |
| 389 | pub fn downsample(samples: &[(i64, f64)], window_ms: i64) -> Vec<(i64, f64)> { |
| 390 | if samples.is_empty() || window_ms <= 0 { |
| 391 | return Vec::new(); |
| 392 | } |
| 393 | |
| 394 | let mut result = Vec::new(); |
| 395 | let mut window_start = (samples[0].0 / window_ms) * window_ms; |
| 396 | let mut window_sum = 0.0; |
| 397 | let mut window_count = 0u64; |
| 398 | |
| 399 | for &(ts, val) in samples { |
| 400 | let this_window = (ts / window_ms) * window_ms; |
| 401 | if this_window != window_start { |
| 402 | if window_count > 0 { |
| 403 | result.push((window_start, window_sum / window_count as f64)); |
| 404 | } |
| 405 | window_start = this_window; |
| 406 | window_sum = 0.0; |
| 407 | window_count = 0; |
| 408 | } |
| 409 | window_sum += val; |
| 410 | window_count += 1; |
| 411 | } |
| 412 | |
| 413 | if window_count > 0 { |
| 414 | result.push((window_start, window_sum / window_count as f64)); |
| 415 | } |
| 416 | |
| 417 | result |
| 418 | } |
| 419 | |
| 420 | // ── Tests ───────────────────────────────────────────────────────────────────── |
| 421 |