OpenCV C++多线程加速

anc*_*jic 5 c++ multithreading opencv

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

Mat img0; // 1280x960 grayscale
Run Code Online (Sandbox Code Playgroud)

-

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;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

结果:

Single thread 0.0458856
Multi thread 0.0329856
Run Code Online (Sandbox Code Playgroud)

加速几乎不引人注意.

我的处理器是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
Run Code Online (Sandbox Code Playgroud)

-

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;
Run Code Online (Sandbox Code Playgroud)

而且我得到了更好的结果:

Multi thread Sectored 0.0232881
Run Code Online (Sandbox Code Playgroud)

所以,当我跑步时,我看起来正在创建960个线程

parallel_for(0, img0.rows, ...
Run Code Online (Sandbox Code Playgroud)

而且效果不佳.

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

Mar*_*ica 1

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

您需要安排您的代码,以便所有四个核心同时在同一位内存上工作(我假设您实际上并没有尝试优化此代码 - 这只是一个简单的示例)。

编辑:在最后一个括号中插入关键的“不”。