What is the fastest library/algorithm for calculating simple moving average? I wrote my own, but it takes too long on 330 000 items decimal dataset.
How aboutQueue
?
using System.Collections.Generic;
using System.Linq;
public class MovingAverage
{
private readonly Queue _queue;
private readonly int _period;
public MovingAverage(int period)
{
_period = period;
_queue = new Queue(period);
}
public decimal Compute(decimal x)
{
if (_queue.Count >= _period)
{
_queue.Dequeue();
}
_queue.Enqueue(x);
return _queue.Average();
}
}
Usage:
MovingAverage ma = new MovingAverage(3);
foreach(var val in new decimal[] { 1,2,3,4,5,6,7,8,9 })
{
Console.WriteLine(ma.Compute(val));
}