OpenCV C ++多线程加速

时间:2015-12-12 15:31:56

标签: c++ multithreading opencv

对于以下代码,这里有一些上下文。

Mat img0; // 1280x960 grayscale

-

timer.start();
for (int i = 0; i < img0.rows; i++)
{
    vector<double> v;
    uchar* p = img0.ptr<uchar>(i);
    for (int j = 0; j < img0.cols; ++j)
    {
        v.push_back(p[j]);
    }
}
cout << "Single thread " << timer.end() << endl;

timer.start();
concurrency::parallel_for(0, img0.rows, [&img0](int i) {
    vector<double> v;
    uchar* p = img0.ptr<uchar>(i);
    for (int j = 0; j < img0.cols; ++j)
    {
        v.push_back(p[j]);
    }
});
cout << "Multi thread " << timer.end() << endl;

结果:

Single thread 0.0458856
Multi thread 0.0329856

加速很难说明。

我的处理器是Intel i5 3.10 GHz

RAM 8 GB DDR3

修改

我尝试了一种稍微不同的方法。

vector<Mat> imgs = split(img0, 2,1); // `split` is my custom function that, in this case, splits `img0` into two images, its left and right half

-

timer.start();
concurrency::parallel_for(0, (int)imgs.size(), [imgs](int i) {
    Mat img = imgs[i];
    vector<double> v;
    for (int row = 0; row < img.rows; row++)
    {
        uchar* p = img.ptr<uchar>(row);
        for (int col = 0; col < img.cols; ++col)
        {
            v.push_back(p[col]);
        }
    }

});
cout << " Multi thread Sectored " << timer.end() << endl;

我得到了更好的结果:

Multi thread Sectored 0.0232881

所以,当我跑

时,看起来我正在创建960个线程
parallel_for(0, img0.rows, ...

这并没有奏效。

(我必须补充一点,肯尼的评论是正确的。不要过多地关注我在这里说的具体数字。当测量这些小间隔时,有很大的变化。但总的来说,我在编辑中写的内容,关于将图像分成两半,与旧方法相比改进了性能。)

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您受到内存带宽的限制。你的第二个片段基本上是从整个图像中读取的,而且必须从主存储器中读出到缓存中。 (或者从L2缓存进入L1缓存)。

你需要安排你的代码,以便所有四个内核同时处理相同的内存(我认为你实际上试图优化这个代码 - 这只是一个简单的例子)。

编辑:在最后的括号内插入关键的“not”。