【问题标题】:Optimize branched for loop in openCL优化 openCL 中的分支 for 循环
【发布时间】:2018-10-15 10:48:58
【问题描述】:

我有一个类似这样的内核代码

__kernel fn(***){
    //X,Y would be image cordinates
    int x = get_global_id(0);
    int y = get_global_id(1);

    //Initialize pixel value
    int c =  -5 + x * dx;
    int d =  -5 + y * dy;

    int k=0;
    for(; k< 500; k++){
        //Perform Some Calculations using c and d
        //Most of the calculations happen here
        if(val > threshold)
            break;
    }
    //Write data based on k
    out[x*width+j] = k;
}

我有一种感觉,因为大多数计算都发生在 for 循环中,并且随着 for 循环创建分支,工作组中的一些工作项完成了它们的内核执行并等待整个工作组完成。

如果输出基于执行计数器 k,如何优化?

【问题讨论】:

    标签: c++ opencl


    【解决方案1】:

    即使你删除了 for 循环也会有一个分支

    if(val > threshold)
        break;
    

    它将由编译器生成,以查看是否应该继续循环。虽然我们可以删除在 for 循环中创建的额外分支。

    k += static_cast<int>(val > threshold) * 500;
    

    如果val &gt; threshold,这将使k 增加500,因此退出检查k 是否达到所需值的同一分支中的循环,而无需额外的分支。根据循环内的计算量,这可能无关紧要。

    【讨论】:

      猜你喜欢
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2012-12-23
      • 2017-09-20
      • 2017-02-21
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多