【发布时间】:2018-09-04 08:17:16
【问题描述】:
我在 Matlab 和 C++ 中制定了一个相当大的优化问题来比较计算时间。我原以为通过将代码转换为 C++,我会减少程序的计算时间,但事实并非如此。这是因为我缺乏 C++ 经验,还是在这种特定情况下,Matlab 实际上可以快 6-7 倍?下面提供了我的代码的 sn-p。
/*
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();
我已经提供了 cmets,我试图在其中加速我的代码。相应的 Matlab 代码如下所示:
CombArr - 单个矩阵 ncams - 单人
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 倍的时间来计算代码?
【问题讨论】:
-
您是否启用了 C++ 编译器的优化?
-
你是如何编译你的代码的?你已经在发布模式下编译了你的代码,对吧?是否将优化级别设置为 3(编译选项 -O3)?
-
combarr[m][n] - matlab 生成的代码将矩阵表示为一维数组。它的方式更快。我怀疑这会导致 6 倍的差异,但我认为这是你应该考虑优化的第一件事。阅读有关矢量化循环的信息(我希望我使用了正确的术语,英语不是我的第一语言)
-
啊,那些仍然认为 MATLAB 很慢的人...... MATLAB 具有 JIT 编译器,在某些方面它比您在 C 中可能执行的任何幼稚实现都要快得多. “早期优化是万恶之源”,你确实做到了,找到了这一切的罪恶!另外,不要打勾,正确分析代码(使用分析器工具),看看什么是快什么是慢
-
使用
timeit代替tic/toc。
标签: c++ matlab optimization