我应结合两个相似的内核与'如果'的语句,冒着性能损失? [英] Should I unify two similar kernels with an 'if' statement, risking performance loss?

查看:101
本文介绍了我应结合两个相似的内核与'如果'的语句,冒着性能损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2非常相似的核函数,在这个意义上,code是几乎相同的,但有轻微的差别。目前,我有2个选择:

I have 2 very similar kernel functions, in the sense that the code is nearly the same, but with a slight difference. Currently I have 2 options:


  • 写2不同的方法(但非常相似的)

  • 写入单个内核,并把在不同的code块的if / else语句

多少会if语句影响我的算法性能?结果
我知道,没有分支,因为在所有块的所有线程将进入无论是如果,还是别的。结果
因此,将一个单一的if语句降低我的表现如果内核函数被调用了很多次?

How much will an if statement affect my algorithm performance?
I know that there is no branching, since all threads in all blocks will enter either the if, or the else.
So will a single if statement decrease my performance if the kernel function is called a lot of times?

推荐答案

您有第三种选择,这是用C ++模板,使这是在如果/ switch语句模板参数使用的变量。实例你需要的内核的各个版本,那么你有多个内核做不同的事情,没有分支发散或条件评估担心,因为编译器优化掉死code和它的分支。

You have a third alternative, which is to use C++ templating and make the variable which is used in the if/switch statement a template parameter. Instantiate each version of the kernel you need, and then you have multiple kernels doing different things with no branch divergence or conditional evaluation to worry about, because the compiler will optimize away the dead code and the branching with it.

也许是这样的:

template<int action>
__global__ void kernel()
{
    switch(action) {
       case 1:
       // First code
       break;

       case 2:
       // Second code
       break;
    }
}

template void kernel<1>();
template void kernel<2>();

这篇关于我应结合两个相似的内核与'如果'的语句,冒着性能损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆