我一直在研究 AVX2 指令集的新收集指令的使用。具体来说,我决定对一个简单的问题进行基准测试,其中一个浮点数组被置换并添加到另一个。在 c 中,这可以实现为
void vectortest(double * a,double * b,unsigned int * ind,unsigned int N)
{
int i;
for(i=0;i<N;++i)
{
a[i]+=b[ind[i]];
}
}
我用 g++ -O3 -march=native 编译这个函数。现在,我以三种方式在汇编中实现它。为简单起见,我假设数组 N 的长度可以被 4 整除。简单的非向量化实现:
align 4
global vectortest_asm
vectortest_asm:
;; double * a = rdi
;; double * b = rsi
;; unsigned int * ind = rdx
;; unsigned int N = rcx
push rax
xor rax,rax
loop: sub rcx, 1
mov eax, [rdx+rcx*4] ;eax = ind[rcx]
vmovq xmm0, [rdi+rcx*8] ;xmm0 = a[rcx]
vaddsd xmm0, [rsi+rax*8] ;xmm1 += b[rax] ( and b[rax] = b[eax] = b[ind[rcx]])
vmovq [rdi+rcx*8], xmm0
cmp rcx, 0
jne loop
pop rax
ret
没有收集指令的循环向量化:
loop: sub rcx, 4
mov eax,[rdx+rcx*4] ;first load the values from array b to xmm1-xmm4
vmovq xmm1,[rsi+rax*8]
mov eax,[rdx+rcx*4+4]
vmovq xmm2,[rsi+rax*8]
mov eax,[rdx+rcx*4+8]
vmovq xmm3,[rsi+rax*8]
mov eax,[rdx+rcx*4+12]
vmovq xmm4,[rsi+rax*8]
vmovlhps xmm1,xmm2 ;now collect them all to ymm1
vmovlhps xmm3,xmm4
vinsertf128 ymm1,ymm1,xmm3,1
vaddpd ymm1, ymm1, [rdi+rcx*8]
vmovupd [rdi+rcx*8], ymm1
cmp rcx, 0
jne loop
最后,使用 vgatherdpd 的实现:
loop: sub rcx, 4
vmovdqu xmm2,[rdx+4*rcx] ;load the offsets from array ind to xmm2
vpcmpeqw ymm3,ymm3 ;set ymm3 to all ones, since it acts as the mask in vgatherdpd
vgatherdpd ymm1,[rsi+8*xmm2],ymm3 ;now gather the elements from array b to ymm1
vaddpd ymm1, ymm1, [rdi+rcx*8]
vmovupd [rdi+rcx*8], ymm1
cmp rcx, 0
jne loop
我在一台装有 Haswell cpu (Xeon E3-1245 v3) 的机器上对这些功能进行了基准测试。一些典型的结果是(以秒为单位的时间):
Array length 100, function called 100000000 times.
Gcc version: 6.67439
Nonvectorized assembly implementation: 6.64713
Vectorized without gather: 4.88616
Vectorized with gather: 9.32949
Array length 1000, function called 10000000 times.
Gcc version: 5.48479
Nonvectorized assembly implementation: 5.56681
Vectorized without gather: 4.70103
Vectorized with gather: 8.94149
Array length 10000, function called 1000000 times.
Gcc version: 7.35433
Nonvectorized assembly implementation: 7.66528
Vectorized without gather: 7.92428
Vectorized with gather: 8.873
gcc 和非向量化汇编版本非常接近。(我还检查了 gcc 的汇编输出,这与我的手动编码版本非常相似。)矢量化对小数组有一些好处,但对大数组来说速度较慢。最大的惊喜(至少对我来说)是使用 vgatherpdp 的版本太慢了。所以,我的问题是,为什么?我在这里做傻事吗?有人可以提供一个示例,其中收集指令实际上会比仅执行多个加载操作带来性能优势吗?如果不是,那么实际上有这样的指令有什么意义?
如果有人想尝试一下,可以在https://github.com/vanhala/vectortest.git上找到测试代码,包括 g++ 和 nasm 的 makefile 。