我是否应该使用“if"语句来统一两个相似的内核,从而冒性能损失的风险? [英] Should I unify two similar kernels with an 'if' statement, risking performance loss?

查看:21
本文介绍了我是否应该使用“if"语句来统一两个相似的内核,从而冒性能损失的风险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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:

  • 编写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>();

这篇关于我是否应该使用“if"语句来统一两个相似的内核,从而冒性能损失的风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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