MCPcopy Create free account
hub / github.com/NodeDB-Lab/nodedb / downsample

Function downsample

nodedb/src/engine/timeseries/reader.rs:389–418  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

387/// one (timestamp, avg_value) per window. The timestamp is the start
388/// of the window.
389pub 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

Callers 2

downsample_basicFunction · 0.85
downsample_metricsMethod · 0.85

Calls 2

is_emptyMethod · 0.45
pushMethod · 0.45

Tested by 1

downsample_basicFunction · 0.68