【发布时间】:2021-01-03 11:19:50
【问题描述】:
尝试使用 AVX 来提高以下性能
__declspec(dllexport) void __cdecl calculate_quantized_vertical_values(long length, float min, float step, float* source, unsigned long* destination)
{
for (long i = 0; i < length; i++)
{
destination[i] = (source[i] - min) / step;
}
}
将其替换为
__declspec(dllexport) void __cdecl calculate_quantized_vertical_values_avx(long length, float min, float step, float* source, unsigned long* destination)
{
long multiple8end = ((long)(length / 8)) * 8;
__m256 min256 = _mm256_broadcast_ss((const float*)&min);
__m256 step256 = _mm256_broadcast_ss((const float*)&step);
for (long i = 0; i < multiple8end; i+=8)
{
__m256 value256 = _mm256_load_ps((const float*)(source + i));
__m256 offset256 = _mm256_sub_ps(value256, min256);
__m256 floatres256 = _mm256_div_ps(offset256, step256);
__m256i long256 = _mm256_cvttps_epi32(floatres256);
_mm256_store_si256((__m256i*)(destination + i), long256);
}
for (long i = multiple8end; i < length; i ++)
{
destination[i] = (source[i] - min) / step;
}
}
原始循环大约需要 330 毫秒,我的 55M 元素源数组和循环的内容编译为
loc_180001050:
movss xmm0, dword ptr [r10+rcx-4]
subss xmm0, xmm3
divss xmm0, xmm2
cvttss2si rax, xmm0
mov [rcx-4], eax
movss xmm1, dword ptr [r10+rcx]
subss xmm1, xmm3
divss xmm1, xmm2
cvttss2si rax, xmm1
mov [rcx], eax
movss xmm0, dword ptr [r10+rcx+4]
subss xmm0, xmm3
divss xmm0, xmm2
cvttss2si rax, xmm0
mov [rcx+4], eax
movss xmm1, dword ptr [r10+rcx+8]
subss xmm1, xmm3
divss xmm1, xmm2
cvttss2si rax, xmm1
mov [rcx+8], eax
add rcx, 10h
sub r8, 1
jnz short loc_180001050
AVX 循环在相同的 55M 元素源数组上花费大约 170ms,并且(主)循环的内容编译为:
loc_180001160:
vmovups ymm0, ymmword ptr [r8+rdx]
lea rdx, [rdx+20h]
vsubps ymm1, ymm0, ymm6
vdivps ymm2, ymm1, ymm7
vcvttps2dq ymm3, ymm2
vmovdqu ymmword ptr [rdx-20h], ymm3
sub rax, 1
jnz short loc_180001160
所以 AVX 有性能改进,但我想知道是否有可能获得更显着的性能改进,或者这是关于此特定计算的限制
编辑:我还应该提到,如果有任何不同,我将从 .NET 应用程序调用这些 DLL 函数。
编辑: 理想情况下,我希望 unsigned char 数组用于 destination,但现在坚持使用 int32,因为我还没有找到实现 float 的方法 -> @987654329 @ AVX 转换
如果可以提高性能,那么乘以 1.f/step 而不是除以 step 对我来说应该没问题
【问题讨论】:
-
_mm256_cvttps_epi32将转换为签名的int32,您的签名表明您希望unsigned long作为输出,这是有意的吗? (无论如何,我都会在此处避免使用long——在 64 位宽的 linux 64 位系统上,以防您想移植它)。你真的需要使用除法,还是可以乘以1.f/step? -
@chtz,我已经更新了这个问题。明白了 long vs int32 的观点,我不太可能移植到 Linux,但我会更新
标签: c optimization avx