How to calculate simple moving average faster in C#?

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

    Tested with Dotnet Core 3 & Linq:

    int period = 20;
    for(int k=0;data.Count()-period;k++){
       decimal summe = data.Skip(k).Take(period).Sum();
       summe /= (decimal)period;
    }
    

    It does rely on Linq and its internal optimization, did not time it.
    Uses Skip() and Take() as a "rangeBetween" solution for moving average and then divide the summe by the period quantity.
    *The for loop is upper capped to avoid incomplete sum operations.
    Reference (C# Microsoft): Skip(), Take(), Sum();

提交回复
热议问题