Username
Username

Reputation: 171

Calculating averages of a vector with increasing size

I have a rendering function that runs hundreds of times per second, and it tells me how many milliseconds each frame takes to draw.

I made a function to calculate the current render speed average of all the frames, which uses an std::vector to hold all the previous frames.

However, every time I run my program the vector that stores the averages becomes huge and takes up an increasing amount of memory, along with slowing down my program by almost 10 times (draw speed).

Averaging function (please note I am a C++ beginner):

double average(std::vector<double> input_vector)
{
    double total = 0;

        for(unsigned int i = 0; i < input_vector.size(); i++)
        {
            total += input_vector.at(i);
        }

    return (total / (double)input_vector.size());
}

Can someone help me fix this?

Thank you

Upvotes: 0

Views: 121

Answers (1)

Dai
Dai

Reputation: 155290

Given the definition of arithmetic mean is sum( n ) / count( n ) you don't need to store every value of n in order to recompute the running mean, you only need the current sum and the current count, like so:

double runningMean(double newValue) {
    static double sum = 0;
    static double count = 0;

    count++;
    sum += newValue;

    return sum / count;
}

No vector needed at all.

Upvotes: 3

Related Questions