【问题标题】:C++ time spent allocating vectors分配向量所花费的 C++ 时间
【发布时间】:2026-02-05 00:35:01
【问题描述】:

我正在尝试加速一段总共运行 150,000,000 次的代码。

我使用“非常困”对其进行了分析,这表明代码在这三个区域中花费的时间最多,如图所示:

代码如下:

double nonLocalAtPixel(int ymax, int xmax, int y, int x , vector<nodeStructure> &nodeMST, int squareDimension, Mat &inputImage) {

    vector<double> nodeWeights(8,0);
    vector<double> nodeIntensities(8,0);
    bool allZeroWeights = true;
    int numberEitherside = (squareDimension - 1) / 2;
    int index = 0;
    for (int j = y - numberEitherside; j < y + numberEitherside + 1; j++) {
        for (int i = x - numberEitherside; i < x + numberEitherside + 1; i++) {

            // out of range or the centre pixel
            if (j<0 || i<0 || j>ymax || i>xmax || (j == y && i == x)) {
                index++;
                continue;
            }
            else {
                int centreNodeIndex = y*(xmax+1) + x;
                int thisNodeIndex = j*(xmax+1) + i;

                // add to intensity list
                Scalar pixelIntensityScalar = inputImage.at<uchar>(j, i);
                nodeIntensities[index] = ((double)*pixelIntensityScalar.val);
                // find weight from p to q
                float weight = findWeight(nodeMST, thisNodeIndex, centreNodeIndex);
                if (weight!=0 && allZeroWeights) {
                    allZeroWeights = false;
                }
                nodeWeights[index] = (weight);
                index++;
            }
        }
    }


    // find min b
    int minb = -1;
    int bCost = -1;

    if (allZeroWeights) {
        return 0;
    }
    else {
        // iteratate all b values 
        for (int i = 0; i < nodeWeights.size(); i++) {
            if (nodeWeights[i]==0) {
                continue;
            }
            double thisbCost = nonLocalWithb(nodeIntensities[i], nodeIntensities, nodeWeights);

            if (bCost<0 || thisbCost<bCost) {
                bCost = thisbCost;
                minb = nodeIntensities[i];
            }
        }
    }
    return minb;
}

首先,我假设Very Sleepy表示的花费时间意味着大部分时间都花在了分配向量和删除向量上?

其次,有什么建议可以加快这段代码的速度吗?

谢谢

【问题讨论】:

  • 如果向量是固定大小的,为什么不使用std::array(几乎零分配时间)?
  • 您是否启用了优化器?
  • findWeight(nodeMST, thisNodeIndex, centreNodeIndex); 是按值传递还是按引用传递? nodeMST 不是 const 引用是否有原因?
  • 当我使用 std::array 时,我得到一个堆栈溢出错误,我不知道为什么。我更改的唯一代码行是初始化向量和 nonLocalWithB 参数以接受数组的两行。
  • 回应退休忍者。 findWeight 通过引用传递 nodeMST,因为它非常大。我不只是将其设为 const 引用的优点是什么?每次我运行这段代码时它都会改变它的值。

标签: c++ algorithm performance


【解决方案1】:
  • 使用 std::array
  • 如果可能的话,通过将向量作为函数的参数或全局变量传递来重用向量(不知道代码的结构,所以我需要更多信息)
  • 分配一个大小为 16 的向量,而不是两个大小为 8 的向量。将减少内存碎片
  • 如果 findWeight 是线程安全的,则使用并行性(您也需要提供更多详细信息)

【讨论】:

    最近更新 更多