gpt4 book ai didi

c - 有符号整数的谓词 "less than or equal"的高效并行字节计算

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:23:42 25 4
gpt4 key购买 nike

<分区>

在各种情况下,例如生物信息学,对字节大小的整数进行计算就足够了。为了获得最佳性能,许多处理器架构提供 SIMD 指令集(例如 MMX、SSE、AVX),它将寄存器划分为字节、半字和字大小的组件,然后分别对相应的组件执行算术、逻辑和移位操作。

但是,某些架构不提供此类 SIMD 指令,需要对其进行仿真,这通常需要大量的位操作。目前,我正在研究 SIMD 比较,特别是有符号字节大小整数的并行比较。我有一个我认为使用可移植 C 代码非常有效的解决方案(请参阅下面的函数 vsetles4)。它基于 2000 年彼得·蒙哥马利 (Peter Montgomery) 在 newsgroup posting 中所做的观察。 , (A+B)/2 = (A AND B) + (A XOR B)/2 在中间计算中没有溢出。

这个特定的仿真代码(函数 vsetles4)能否进一步加速?首先订购任何基本操作数较少的解决方案都符合条件。我正在寻找可移植 ISO-C99 中的解决方案,而不使用特定于机器的内在函数。大多数架构都支持 ANDN (a & ~b),因此就效率而言,可以假定这可作为单个操作使用。

#include <stdint.h>

/*
vsetles4 treats its inputs as arrays of bytes each of which comprises
a signed integers in [-128,127]. Compute in byte-wise fashion, between
corresponding bytes of 'a' and 'b', the boolean predicate "less than
or equal" as a value in [0,1] into the corresponding byte of the result.
*/

/* reference implementation */
uint32_t vsetles4_ref (uint32_t a, uint32_t b)
{
uint8_t a0 = (uint8_t)((a >> 0) & 0xff);
uint8_t a1 = (uint8_t)((a >> 8) & 0xff);
uint8_t a2 = (uint8_t)((a >> 16) & 0xff);
uint8_t a3 = (uint8_t)((a >> 24) & 0xff);
uint8_t b0 = (uint8_t)((b >> 0) & 0xff);
uint8_t b1 = (uint8_t)((b >> 8) & 0xff);
uint8_t b2 = (uint8_t)((b >> 16) & 0xff);
uint8_t b3 = (uint8_t)((b >> 24) & 0xff);
int p0 = (int32_t)(int8_t)a0 <= (int32_t)(int8_t)b0;
int p1 = (int32_t)(int8_t)a1 <= (int32_t)(int8_t)b1;
int p2 = (int32_t)(int8_t)a2 <= (int32_t)(int8_t)b2;
int p3 = (int32_t)(int8_t)a3 <= (int32_t)(int8_t)b3;

return (((uint32_t)p3 << 24) | ((uint32_t)p2 << 16) |
((uint32_t)p1 << 8) | ((uint32_t)p0 << 0));
}

/* Optimized implementation:

a <= b; a - b <= 0; a + ~b + 1 <= 0; a + ~b < 0; (a + ~b)/2 < 0.
Compute avg(a,~b) without overflow, rounding towards -INF; then
lteq(a,b) = sign bit of result. In other words: compute 'lteq' as
(a & ~b) + arithmetic_right_shift (a ^ ~b, 1) giving the desired
predicate in the MSB of each byte.
*/
uint32_t vsetles4 (uint32_t a, uint32_t b)
{
uint32_t m, s, t, nb;
nb = ~b; // ~b
s = a & nb; // a & ~b
t = a ^ nb; // a ^ ~b
m = t & 0xfefefefe; // don't cross byte boundaries during shift
m = m >> 1; // logical portion of arithmetic right shift
s = s + m; // start (a & ~b) + arithmetic_right_shift (a ^ ~b, 1)
s = s ^ t; // complete arithmetic right shift and addition
s = s & 0x80808080; // MSB of each byte now contains predicate
t = s >> 7; // result is byte-wise predicate in [0,1]
return t;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com