You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用并行化或SSE的前提下优化C++分箱统计循环

优化非并行/SSE下的C++分箱代码性能

我正尝试在不使用并行化或SSE技术的前提下优化一段C++代码。当前在O2优化级别下,关键代码段在我的PC上运行耗时约20ms,即便对于约1700万次迭代来说,这个耗时也偏长。较慢的核心代码段如下:

for (int d = 0; d < numDims; d++)
{
    for (int i = 0; i < numNodes; i++)
    {
        bins[d][(int) (floodVals[d][i] * binSteps)]++;
    }
}

更新:改用迭代器后运行时间降至17ms,代码如下:

for (int d = 0; d < numDims; d++)
{
    std::vector<float>::iterator floodIt;
    for (floodIt = floodVals[d].begin(); floodIt < floodVals[d].end(); floodIt++)
    {
        bins[d][(int) (*floodIt * binSteps)]++;
    }
}

完整测试代码如下:

#include <vector>
#include <random>
#include <iostream>
#include <chrono>

int main()
{
    // Initialize random normalized input [0, 1)
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dist(0, 0.99999);

    // Initialize dimensions
    const int numDims = 130;
    const int numNodes = 130000;
    const int binSteps = 30;

    // Make dummy data
    std::vector<std::vector<float>> floodVals(numDims, std::vector<float>(numNodes));

    for (int d = 0; d < numDims; d++)
    {
        for (int i = 0; i < numNodes; i++)
        {
            floodVals[d][i] = dist(gen);
        }
    }

    // Initialize binning
    std::vector<std::vector<int>> bins(numDims, std::vector<int>(binSteps, 0));

    // Time critical section of code
    auto start = std::chrono::high_resolution_clock::now();

    for (int d = 0; d < numDims; d++)
    {
        for (int i = 0; i < numNodes; i++)
        {
            bins[d][(int) (floodVals[d][i] * binSteps)]++;
        }
    }

    auto finish = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = finish - start;
    std::cout << "Elapsed: " << elapsed.count() * 1000 << " ms" << std::endl;

    return 0;
}

内容的提问来源于stack exchange,提问作者Taylee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:45:27