【问题标题】:How can I optimize this function which handles large c++ vectors?如何优化这个处理大型 c++ 向量的函数?
【发布时间】:2013-10-20 04:36:10
【问题描述】:

根据 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 的处理器功率。

也许这与它必须在向量内跳转而不是仅仅线性访问它们有关?不过我真的不知道。有什么想法可以优化吗?

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

【问题讨论】:

  • 这是一个真正的瓶颈吗?还是你只是看了一下就得出“它消耗太多CPU”的结论?
  • 是的,它用于实时音频应用程序,并且可以听到性能问题
  • 你知道东西可以作为参考传递
  • @Ed Heal 抱歉,这是一个错误,它是通过引用传递的。已编辑。
  • 您的编译器优化设置是否已开启并已启动?

标签: c++ optimization fft


【解决方案1】:

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

【讨论】:

  • 是的!早该想到去寻找,整个程序现在运行速度快了 10 倍。
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 2018-06-24
  • 2018-02-21
  • 2013-07-02
  • 2018-05-31
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多