How to calculate simple moving average faster in C#?

后端 未结 14 2605
囚心锁ツ
囚心锁ツ 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 07:05

    Your main problem is that you throw away too much information for each iteration. If you want to run this fast, you need to keep a buffer of the same size as the frame length.

    This code will run moving averages for your whole dataset:

    (Not real C# but you should get the idea)

    decimal buffer[] = new decimal[period];
    decimal output[] = new decimal[data.Length];
    current_index = 0;
    for (int i=0; i

    Please note that it may be tempting to keep a running cumsum instead of keeping the whole buffer and calculating the value for each iteration, but this does not work for very long data lengths as your cumulative sum will grow so big that adding small additional values will result in rounding errors.

提交回复
热议问题