我应该用“if"语句统一两个相似的内核,冒着性能损失的风险吗?
我有 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 种不同的方法(但非常相似)
- 编写单个内核并将不同的代码块放在 if/else 语句中
if 语句会在多大程度上影响我的算法性能?
我知道没有分支,因为所有块中的所有线程都将进入 if 或 else.
那么如果内核函数被多次调用,单个 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++ 模板并将 if/switch 语句中使用的变量作为模板参数.实例化您需要的每个版本的内核,然后您有多个内核做不同的事情,无需担心分支分歧或条件评估,因为编译器将优化死代码并使用它进行分支.
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>();
相关文章