我需要为代码下面的示例提供建议,这需要大量时间进行处理。我正在开发OpenCV上的项目,并且有这样的代码块(其中一些是图片)。我应该用什么来提高速度?比如,OpenMP或TBB(这是OpenCV中的新功能,更复杂,可能是一些更有用的示例)或GPU(实现整个项目)或Boost库或其他我不了解第三方库。
我之前没有在c ++上编写多线程
感谢您现在的帮助
示例代码段:
for ( int j = 0; j < 90000000; j++ )
for ( int i = 0; i < 90000000; i++ )
for ( int k = 0; k < 90000000; k++ )
// float point operations
答案 0 :(得分:3)
首先,您应确保对您的记忆进行线性访问。例如,如果你有一个矩阵:
cv::Mat mat(nrows, ncols, CV_32FC1);
线性访问是:
for(int r = 0; r < mat.rows; r++)
{
for(int c = 0; c < mat.cols; c++)
{
mat.at<float>(r,c) ... do something
}
}
没有线性访问且速度会慢得多:
for(int c = 0; c < mat.cols; c++)
{
for(int r = 0; r < mat.rows; r++)
{
mat.at<float>(r,c) ... do something
}
}
因为它拒绝缓存。此外,作为OpenMP或TBB的技术是优选的。但是,如果您能够使用8位数值进行计算,那么通过Streaming SIMD Extensions(SSE)进行并行化可以将每个内核的代码提高8倍。
答案 1 :(得分:1)
OpenMP是最简单的选择之一。我们可以只有一些预处理器来并行化循环。 以下是使用OpenMP
执行点积的简单示例double Dot( int n, double x[], double y[] )
{
int i;
double dot_product = 0.0;
# pragma omp parallel \
shared ( n, x, y ) \
private ( i )
# pragma omp for reduction ( + : dot_product )
for ( i = 0; i < n; i++ )
{
dot_product = dot_product + x[i] * y[i];
}
return dot_product;
}