我正在用 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/