如何优化这个处理大型 c++ 向量的函数

How can I optimize this function which handles large c++ vectors?

本文关键字:大型 处理 c++ 向量 函数 何优化 优化      更新时间:2023-10-16

根据Visual Studio的性能分析器,以下函数正在消耗在我看来异常大的处理器能力,因为它所做的只是从多个向量中添加1到3个数字,并将结果存储在其中一个向量中。

//Relevant class members:
//vector<double> cache (~80,000);
//int inputSize;
//Notes:
//RealFFT::real is a typedef for POD double.
//RealFFT::RealSet is a wrapper class for a c-style array of RealFFT::real. 
//This is because of the FFT library I'm using (FFTW).
//It's bracket operator is overloaded to return a const reference to the appropriate array element
vector<RealFFT::real> Convolver::store(vector<RealFFT::RealSet>& data)
{
    int cr = inputSize; //'cache' read position
    int cw = 0; //'cache' write position
    int di = 0; //index within 'data' vector (ex. data[di])
    int bi = 0; //index within 'data' element (ex. data[di][bi])
    int blockSize = irBlockSize();
    int dataSize = data.size();
    int cacheSize = cache.size();
    //Basically, this takes the existing values in 'cache', sums them with the
    //values in 'data' at the appropriate positions, and stores them back in
    //the cache at a new position.
    while (cw < cacheSize)
    {
        int n = 0;
        if (di < dataSize)
            n = data[di][bi];
        if (di > 0 && bi < inputSize)
            n += data[di - 1][blockSize + bi];
        if (++bi == blockSize)
        {
            di++;
            bi = 0;
        }
        if (cr < cacheSize)
            n += cache[cr++];
        cache[cw++] = n;
    }
    //Take the first 'inputSize' number of values and return them to a new vector.
    return Common::vecTake<RealFFT::real>(inputSize, cache, 0);
}

当然,所讨论的向量的大小约为 80,000 个项目,但相比之下,将复数的相似向量相乘的函数(复数乘法需要 4 次实数乘法和 2 次加法)消耗大约 1/3 的处理器功率。

也许它与它必须在向量内跳来跳去而不是只是线性访问它们有关?不过我真的不知道。关于如何优化它的任何想法?

编辑:我应该提到我也尝试编写函数来线性访问每个向量,但这需要更多的总迭代,实际上这种方式的性能更差。

根据需要启用编译器优化。 MSVC 指南在这里:http://msdn.microsoft.com/en-us/library/k1ack8f1.aspx