了解MSVS C ++编译器优化

亚历克斯·朱可夫斯基(Alex Zhukovskiy)

我不明白这段代码中发生了什么。C代码是:

#include <stdio.h>

int main()
{
    const int mul = 100;
    int x;
    printf_s("Input a number\r\n");
    scanf_s("%i", &x);
    printf_s("%i/%i = %i\r\n", x, mul, x / mul);
    return 0;
}

我希望生成的程序集将进行一些简单的移位和加/减运算,但是会有一些魔术常数,例如51EB851Fh,乘法等。这是怎么回事?

; int __cdecl main()
_main proc near

x= dword ptr -8
var_4= dword ptr -4

push    ebp
mov     ebp, esp
sub     esp, 8
mov     eax, ___security_cookie
xor     eax, ebp
mov     [ebp+var_4], eax
push    offset Format   ; "Input a number\r\n"
call    ds:__imp__printf_s
lea     eax, [ebp+x]
push    eax
push    offset aI       ; "%i"
call    ds:__imp__scanf_s
mov     ecx, [ebp+x]
mov     eax, 51EB851Fh
imul    ecx
sar     edx, 5
mov     eax, edx
shr     eax, 1Fh
add     eax, edx
push    eax
push    64h
push    ecx
push    offset aIII     ; "%i/%i = %i\r\n"
call    ds:__imp__printf_s
mov     ecx, [ebp+var_4]
add     esp, 1Ch
xor     ecx, ebp        ; cookie
xor     eax, eax
call    @__security_check_cookie@4 ; __security_check_cookie(x)
mov     esp, ebp
pop     ebp
retn
_main endp
汉斯·帕桑特

处理器不是很擅长除法,一个idiv可能需要11到18个周期。与移位和乘法相反,它们通常只需要一个周期。

因此,优化器使用定点数学乘以您的除法,利用32位乘以edx:eax产生64位结果的优势。封底:n / 100 == n * 0.32 / 32 == n *(0.32 * pow(2,32))/ 32 / pow(2,32)。这些部门非常便宜,只是右移。乘数变为0.32 * pow(2,32)〜= 1374389535 == 0x51EB851F

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章