我有 2 个非常相似的内核函数,从某种意义上说,代码几乎相同,但略有不同.目前我有 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:
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>();
这篇关于我是否应该使用“if"语句来统一两个相似的内核,从而冒性能损失的风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!