【发布时间】:2013-03-28 19:12:56
【问题描述】:
首先,我对多线程知之甚少,我很难找到优化此代码的最佳方法,但多线程似乎是我应该走的路。
double
applyFilter(struct Filter *filter, cs1300bmp *input, cs1300bmp *output)
{
long long cycStart, cycStop;
cycStart = rdtscll();
output -> width = input -> width;
output -> height = input -> height;
int temp1 = output -> width;
int temp2 = output -> height;
int width=temp1-1;
int height=temp2 -1;
int getDivisorVar= filter -> getDivisor();
int t0, t1, t2, t3, t4, t5, t6, t7, t8, t9;
int keep0= filter -> get(0,0);
int keep1= filter -> get(1,0);
int keep2= filter -> get(2,0);
int keep3= filter -> get(0,1);
int keep4= filter -> get(1,1);
int keep5= filter -> get(2,1);
int keep6= filter -> get(0,2);
int keep7= filter -> get(1,2);
int keep8= filter -> get(2,2);
//Declare variables before the loop
int plane, row, col;
for (plane=0; plane < 3; plane++) {
for(row=1; row < height ; row++) {
for (col=1; col < width; col++) {
t0 = (input -> color[plane][row - 1][col - 1]) * keep0;
t1 = (input -> color[plane][row][col - 1]) * keep1;
t2 = (input -> color[plane][row + 1][col - 1]) * keep2;
t3 = (input -> color[plane][row - 1][col]) * keep3;
t4 = (input -> color[plane][row][col]) * keep4;
t5 = (input -> color[plane][row + 1][col]) * keep5;
t6 = (input -> color[plane][row - 1][col + 1]) * keep6;
t7 = (input -> color[plane][row][col + 1]) * keep7;
t8 = (input -> color[plane][row + 1][col + 1]) * keep8;
// NEW LINE HERE
t9 = t0 + t1 + t2 + t3 + t4 + t5 + t6 + t7 + t8;
t9 = t9 / getDivisorVar;
if ( t9 < 0 ) {
t9 = 0;
}
if ( t9 > 255 ) {
t9 = 255;
}
output -> color[plane][row][col] = t9;
} ....
所有这些代码很可能都不是必需的,但它确实提供了一些上下文。因此,因为 3 个“for”循环中的第一个仅从 0-2 开始,所以我希望有一种方法可以让底部的两个“for”循环同时运行以获取不同的“平面”值。这甚至可能吗?如果是这样,它真的会让我的程序更快吗?
【问题讨论】:
-
这就是我在简要了解多线程之后的想法,但我认为只要 t0-t9 都以某种方式在线程中是可能的?因为所有其他变量都独立于循环。
-
确保线程中使用的所有内容都是线程本地的,因此您无需担心线程相互踩踏,除了输入和输出数组。对于那些,只需以编程方式确保您永远不会从两个不同的线程读取/写入相同的单元格,这样您就不需要同步。
-
我刚刚使用 4 个平面和 2560x1600 图像进行了尝试。单线程耗时 109 毫秒,4 个线程耗时 47 毫秒。但是由于这个过程非常简单,创建和等待线程的开销实际上已经足够大了,但它仍然将计算所需的时间减少了一半以上。更复杂的循环肯定会从线程中受益更多。正如我所说,在这个例子中不需要任何同步(除了等待线程完成)。
标签: c++ multithreading loops optimization nested-loops