c++ - Matlab 与 C++ 运行时比较

标签 c++ matlab optimization

我正在用 Matlab 和 C++ 制定一个相当大的优化问题来比较计算时间。我本以为通过将代码转换为 C++,我会减少程序的计算时间,但事实并非如此。这是因为我缺乏 C++ 经验,还是在这种特定情况下,Matlab 实际上可以快 6-7 倍?下面提供了我的代码片段。

/*
    Comnum - int
    ky - int
    numcams - int
    outmat - std::vector<std::vector<bool>>
*/
    array_bool bout(ky);
    auto tt = Clock::now();
    array_int sum(comnum);
    for(int m = 0; m < comnum ; m++){
        //array_bool bout(ky);
        std::fill(bout.begin(),bout.end(),false);

        // Fill is faster than looping as shown below
/*
        for(int l = 0 ; l < ky ; l++)
        {
            bout[l] = false;
        }
*/
        for(int n = 0; n < numcams ; n++){
            int ind = combarr[m][n];
            std::transform(bout.begin(),bout.end(),outmat[ind].begin(),bout.begin(),std::plus<bool>());

            // Transform is faster than looping as shown below
/*
            for(int i = 0 ; i < ky ; i++)
            {
                bout[i] = bout[i] | outmat[ind][i];
            }
*/

        }
        // Looping is faster than using accumulate 
//      sum[m] = std::accumulate(bout.begin(),bout.end(),0);


        sumof = 0;

        for(int j = 0; j < ky ; j++)
        {
            if(bout[j] == true) sumof +=1;
        }

        sum[m] = sumof;

    }

    auto ttt = Clock::now();

我在试图加速我的代码的地方提供了评论。相应的 Matlab 代码如下所示:

CombArr - 单矩阵 网络摄像头-单例

t2 = tic; 

for m = 1:length(CombArr)
    bcombs = false(1,ldata);  % Set current combination coverage array to 0

    % Loop through given number of cameras and compute coverage 
    % For given combination (bcombs)
    for n = 1:ncams 
        ind = CombArr(m,n);  
        bcombs(1,1:ldata) = bcombs(1,1:ldata) | b(ind,1:ldata);
    end

    % Compute the sum of covered data points
    sumcurr(m) = single(sum(bcombs(1,1:ldata)));


end
toc(t2)

我知道这可能是一个太长的问题,但我想知道是否有人可以启发我为什么 C++ 使用大约 6 倍的时间来计算代码?

最佳答案

正如评论所指出的,改变我的编译对我来说是对的。使用此编译代码将计算时间减少了 10 倍:

g++ code.cpp -O3 -o test

谢谢大家,这对我很有帮助!

关于c++ - Matlab 与 C++ 运行时比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487182/

相关文章:

javascript - 如何使用 JS 或 Jquery 在加载有 <link> 标记的外部 CSS 文件中定位 @import

c++ - cvCeil() 比标准库快吗?

c++ - 需要独家访问私有(private)类状态的设计建议

C++ mprotect 用于读、写和执行

matlab - 在Matlab中使用svmtrain获得模型后如何找到特征的权重?

c++ - 如何在不调用 Matlab 的情况下从 C++ 应用经过训练的 Matlab 神经网络?

c++ - 在 C++ 中设置控件的颜色,Windows Store Metro App

c++ - 为 Variadic 模板函数推导参数失败

matlab - 如何在 MATLAB 中绘制置信区间?

c - for 循环上的多个 pragma 指令(C 和 VS 2013)