gpt4 book ai didi

c++ - OpenCV C++ 多线程加速

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:22 25 4
gpt4 key购买 nike

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

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

内存 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, ...

但这并不奏效。

(我必须补充一点,Kenney 的评论是正确的。不要与我在这里陈述的具体数字太相关。当测量像这样的小间隔时,会有很大的变化。但总的来说,我在编辑中写的,关于将图像分成两半,与旧方法相比提高了性能。)

最佳答案

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

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

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

关于c++ - OpenCV C++ 多线程加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34241588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com