1

我已经实现了一个简单的统计引擎,使用双端队列返回滚动均值和方差,以提供数据队列。

双端队列由与滚动值数量相等的条目数构成。

当一个新值到达时,最旧的值会从前面弹出,新的值会被推到后面。

我需要确保它不会在内存中增长,因为它预计会作为后台任务运行很长时间。

双端队列是否在使用中的堆上分配?有没有可以用来修复其大小的标志?

我在 RHEL 5.3 上使用 G++ 4.1.2

4

3 回答 3

9

本质上,任何动态大小的容器都从堆中分配内存。另一个问题概述了 deque 的实现

但是在您的特定情况下,队列始终具有相同的大小。如果遇到双端队列问题,使用固定大小数组上的循环缓冲区实现简单的固定大小队列可能会有所帮助。这种实现应该具有从根本上更好的内存行为(因为它从不需要重新分配)。如果不分析数据,很难评估其优势是否值得实施。

于 2011-06-28T13:33:15.550 回答
3

就像提示一样,如果您不需要跟踪值,那么这个很棒的算法非常轻量级(我什至在 8bit micros 上使用它)并且是准确的。

 class RunningStat
{
public:
    RunningStat() : m_n(0) {}

    void Clear()
    {
        m_n = 0;
    }

    void Push(double x)
    {
        m_n++;

        // See Knuth TAOCP vol 2, 3rd edition, page 232
        if (m_n == 1)
        {
            m_oldM = m_newM = x;
            m_oldS = 0.0;
        }
        else
        {
            m_newM = m_oldM + (x - m_oldM)/m_n;
            m_newS = m_oldS + (x - m_oldM)*(x - m_newM);

            // set up for next iteration
            m_oldM = m_newM; 
            m_oldS = m_newS;
        }
    }

    int NumDataValues() const
    {
        return m_n;
    }

    double Mean() const
    {
        return (m_n > 0) ? m_newM : 0.0;
    }

    double Variance() const
    {
        return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 );
    }

    double StandardDeviation() const
    {
        return sqrt( Variance() );
    }

private:
    int m_n;
    double m_oldM, m_newM, m_oldS, m_newS;
};

该算法由 BP Welford 创建,并在 Donald Knuth 的计算机编程艺术,第 2 卷,第 232 页,第 3 版中介绍。

http://www.johndcook.com/standard_deviation.html

于 2011-06-28T13:38:21.383 回答
0

该规范将实现细节留给供应商。但是,由于两端的插入是有效的,因此很可能将其实现为堆上的链接结构。话虽如此,当你从堆中弹出一些东西时,它应该被解构,所以你的总内存使用量不应该增加。

于 2011-06-28T13:34:15.650 回答