Skip to content
This repository has been archived by the owner on Jun 27, 2022. It is now read-only.

Commit

Permalink
Accept iterator as argument to ewma
Browse files Browse the repository at this point in the history
This avoids an intermediate call to collect, providing a small
performance increase.
  • Loading branch information
meqif committed Oct 25, 2015
1 parent e798f8e commit 032e2df
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,7 @@ impl UtpSocket {
/// weighted moving average filter with smoothing factor 0.333 over the
/// current delays in the current window.
fn filtered_current_delay(&self) -> i64 {
let input = self.current_delays.iter().map(|x| x.difference).collect();
let input = self.current_delays.iter().map(|x| x.difference);
ewma(input, 0.333) as i64
}

Expand Down
12 changes: 6 additions & 6 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ pub fn now_microseconds() -> u32 {

/// Calculate the exponential weighted moving average for a vector of numbers, with a smoothing
/// factor `alpha` between 0 and 1. A higher `alpha` discounts older observations faster.
pub fn ewma<T: ToPrimitive>(samples: Vec<T>, alpha: f64) -> f64 {
samples.iter().fold(samples.first().map_or(0.0, |v| v.to_f64().unwrap()),
|avg, sample| alpha * sample.to_f64().unwrap() + (1.0 - alpha) * avg)
pub fn ewma<T: ToPrimitive, I: Iterator<Item=T>>(mut samples: I, alpha: f64) -> f64 {
let first = samples.next().map_or(0.0, |v| v.to_f64().unwrap());
samples.fold(first, |avg, sample| alpha * sample.to_f64().unwrap() + (1.0 - alpha) * avg)
}

/// Returns the absolute difference between two integers.
Expand All @@ -32,19 +32,19 @@ mod test {
fn test_ewma_empty_vector() {
let empty: Vec<u32> = vec!();
let alpha = 1.0/3.0;
assert_eq!(ewma(empty, alpha), 0.0);
assert_eq!(ewma(empty.iter().map(|x| *x), alpha), 0.0);
}

#[test]
fn test_ewma_one_element() {
let input = vec!(1u32);
let alpha = 1.0/3.0;
assert_eq!(ewma(input, alpha), 1.0);
assert_eq!(ewma(input.iter().map(|x| *x), alpha), 1.0);
}

#[test]
fn test_exponential_smoothed_moving_average() {
let input = (1u32..11).collect();
let input = 1u32..11;
let alpha = 1.0/3.0;
let expected = [1.0, 4.0/3.0, 17.0/9.0,
70.0/27.0, 275.0/81.0, 1036.0/243.0, 3773.0/729.0, 13378.0/2187.0,
Expand Down

0 comments on commit 032e2df

Please sign in to comment.