【发布时间】:2017-02-20 13:06:53
【问题描述】:
我想优化我的顺序代码以制作渐变。
主线程计算图像边界的梯度,其他线程分别计算图像块的梯度, 使用 2 个线程和主线程提供的结果比顺序代码更好,但使用超过 2 个线程,但它消耗 更多 时间并且看起来比顺序代码最差。
我试过这段代码来加速渐变过程:
for (int n = 0; n<iter_outer; n++)
{
int chunk = 1 + ((row - 1) / num_threads); //ceiling
int start=0;
int end=0;
//Launch a group of threads
for (int tid = 0; tid < num_threads; ++tid)
{
start = tid * chunk;
end = start + chunk;
t[tid] = thread(gradient, tid, g, vx, vy, row, col, 1, start, end);
}
//Launched from the main;
gradient(1, g, vx, vy, row, col,0, start, end);
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i)
{
t[i].join();
}
}
【问题讨论】:
-
你的机器有几个核心?可能是 2 个?
-
每次在线程之间切换时,都需要时间来设置新的上下文。
-
对于短时间运行的线程,有一点是创建线程(以及在上下文之间切换)的开销抵消了拥有多个线程的速度增益。我怀疑你的图片太小了。
-
想象一下有 1000 个线程 - 程序必须不断地切换上下文以使所有线程都能获得一些工作,这会增加总执行时间
-
为了避免误解我之前的评论:即使您要处理一个巨大的图像,添加线程时您仍然不会看到线性速度增加。这是由于上下文切换的开销增加(正如其他人所指出的那样)。对于给定硬件上的给定工作负载,您可以确定最佳线程数量(例如通过猜测和微调)。
标签: c++ multithreading