如何计算简单移动平均线在C#中更快吗?更快、平均、简单

2023-09-11 00:07:49 作者:ゞ懂↘(1e)

什么是最快的库/算法,计算简单移动平均线?我写我自己,但时间过久的330 000项十进制数据集。

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.

期/时间(ms) 三百分之二十; 一千五百分之六十〇; 三千五分之一百二十零。

下面是我的方法的code:

Here is the code of my method:

public decimal MA_Simple(int period, int ii) {
    if (period != 0 && ii > period) {
        //stp.Start();
        decimal summ = 0;
        for (int i = ii; i > ii - period; i--) {
            summ = summ + Data.Close[i];
        }
        summ = summ / period;
        //stp.Stop();
        //if (ii == 1500) System.Windows.Forms.MessageBox.Show((stp.ElapsedTicks * 1000.0) / Stopwatch.Frequency + " ms");
        return summ;
    } else return -1;
}

Data.Close [] 大小是固定的(1 000 000)十进制阵列。

The Data.Close[] is a fixed size(1 000 000) decimal array.

推荐答案

您的主要问题是,你扔掉太多的信息对每个迭代。 如果你想运行此快,你需要保持同样大小的帧长度的缓冲区。

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.

这code将运行均线为您的整个数据集:

This code will run moving averages for your whole dataset:

(不是真正的C#,但你应该明白了吧)

(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<data.Length; i++)
    {
        buffer[current_index] = data[i]/period;
        decimal ma = 0.0;
        for (int j=0;j<period;j++)
            {
                ma += buffer[j];
            }
        output[i] = ma;
        current_index = (current_index + 1) % period;
    }
return output;

请注意,它可能是很有诱惑力保持运行cumsum,而不是保持整个缓冲区,并计算每个迭代的价值,但是这并不很长的数据长度工作作为您的累计总和将增长如此之大,加入小其他值将导致舍入误差。

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.

 
精彩推荐
图片推荐