SIMD 的优先选择是始终摆脱分支吗?
如果您正在编写一些将由另一个程序运行的 SIMD 代码,那么摆脱分支以提高性能是否总是有利的?我听说即使只是为了避免 if/else 语句等而进行额外的操作仍然要快得多。
我问这个问题是因为我做了一些分支,基本上是这样的:
// axis; x=0, y=1, z=2
float p, q;
if (axis == 0)
{
p = point.y;
q = point.z;
}
else if (axis == 1)
{
p = point.x;
q = point.z;
}
else if (axis == 2)
{
p = point.x;
q = point.y;
}
我可以通过一些巧妙的技巧来避免这种分支吗?
If you are writing some SIMD code that will be run by another program, is it always favorable to get rid of branching to increase performance? I heard that even doing extra operations just to avoid if/else
statements, etc is still much faster.
I ask this because I have some branching that I do that's basically like this:
// axis; x=0, y=1, z=2
float p, q;
if (axis == 0)
{
p = point.y;
q = point.z;
}
else if (axis == 1)
{
p = point.x;
q = point.z;
}
else if (axis == 2)
{
p = point.x;
q = point.y;
}
Can I avoid this kind of branching with some clever trick?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数 SIMD 架构都有特殊指令,可让您根据掩码向量有条件地选择元素。掩码向量通常是 SIMD 比较指令的结果。所以是的,摆脱上面示例中的那种分支非常容易。
您是否确实需要删除任何给定的分支将取决于各种因素,例如分支的可预测性、数据的性质(统计数据)以及有条件执行的代码量。根据经验,无分支是好的,但与大多数规则一样,也有例外。
Most SIMD architectures have special instructions which let you conditionally select elements based on a mask vector. The mask vector is typically the result of a SIMD compare instruction. So yes, it's pretty easy to get rid of the kind of branches that you have in your example above.
Whether you actually need to get rid of any given branch though will depend on various factors such as the predictability of the branch, the nature (statistics) of the data, and how much code is executed conditionally. As a rule of thumb, branchless is good, but as with most rules there are exceptions.