基于比较的条件SSE/AVX加或零元素 [英] Conditional SSE/AVX add or zero elements based on compare

查看:64
本文介绍了基于比较的条件SSE/AVX加或零元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 __ m128 个向量:

v_weight

v_entropy

仅当 v_weight 中的元素不为0f时,我才需要向 v_weight 中添加 v_entropy .

I need to add v_entropy to v_weight only where elements in v_weight are not 0f.

很显然, _mm_add_ps()会添加所有元素.

Obviously _mm_add_ps() adds all elements regardless.

我最多可以编译AVX,但不能编译AVX2.

I can compile up to AVX, but not AVX2.

编辑

我确实知道 v_weight 中有多少个元素将为0(总为0或最后的1、2或3个元素).如果更简单,如何将 v_entropy 中的相应元素归零?

I do know beforehand how many elements in v_weight will be 0 (there will always be either 0 or the last 1, 2, or 3 elements). If it's easier, how do I zero-out the corresponding elements in v_entropy?

推荐答案

cmpeq/cmpgt指令创建一个全为1或全为零的掩码.整个过程如下:

The cmpeq/cmpgt instructions create a mask, all ones or all zeros. The overall process goes as follows:

auto mask=_mm_cmpeq_ps(_mm_setzero_ps(), w);
mask=_mm_andnot_ps(mask, entropy);
w = _mm_add_ps(w, mask);

其他选项仍然是累加,但可以使用blendv在已添加/未添加之间进行选择.

Other option is to accumulate anyway, but use blendv to select between added/not added.

auto w2=_mm_add_ps(e,w);
auto mask=_mm_cmpeq_ps(zero,w);
w=_mm_blendv_ps(w2,w, mask);

第三种选择使用的事实是,当w = 0时w + e = 0

Third option uses the fact that w+e = 0, when w=0

 m=(w==0); // make mask as in above
 w+=e; // add
 w&=~m; // revert adding for w==0

(我正在使用cmpeq而不是cmpneq来使它也可用于整数.)

(I'm using cmpeq instead of cmpneq to make it usable for integers as well.)

这篇关于基于比较的条件SSE/AVX加或零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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