How to calculate simple moving average faster in C#?

后端 未结 14 2510
囚心锁ツ
囚心锁ツ 2020-12-15 06:42

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.

  • period /
14条回答
  •  醉梦人生
    2020-12-15 06:55

    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));
    }
    

提交回复
热议问题