How to calculate simple moving average faster in C#?

后端 未结 14 2596
囚心锁ツ
囚心锁ツ 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:52

    You don't need to keep a running queue. Just pick the latest new entry to the window and drop off the older entry. Notice that this only uses one loop and no extra storage other than a sum.

      // n is the window for your Simple Moving Average
      public List GetMovingAverages(List prices, int n)
      {
        var movingAverages = new double[prices.Count];
        var runningTotal = 0.0d;       
    
        for (int i = 0; i < prices.Count; ++i)
        {
          runningTotal += prices[i].Value;
          if( i - n >= 0) {
            var lost = prices[i - n].Value;
            runningTotal -= lost;
            movingAverages[i] = runningTotal / n;
          }
        }
        return movingAverages.ToList();
      }
    

提交回复
热议问题