理解MSVS C ++编译器优化 [英] Understanding of MSVS C++ compiler optimizations

查看:594
本文介绍了理解MSVS C ++编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I do not understand what is happening in this code. The C code is:

#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 ,乘法等。这里发生了什么?

I expected that the resulting assembly will be some simple shifts and add/sub operations, but there are some magic constants like 51EB851Fh, multiplications, etc. What is happening here?

; 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个周期之间。与移位和乘法相反,它们通常只需要一个周期。

Processors are not very good at dividing, an idiv can take between 11 and 18 cycles. As opposed to shifts and multiplies, they usually only take a single cycle.

因此,优化器通过使用定点数学的乘法来代替你的除法,利用32位乘法产生64位结果到edx:eax。回束包络:n / 100 == n * 0.32 / 32 == n *(0.32 * pow(2,32))/ 32 / pow(2,32)。这些部门非常便宜,只是一个右移。乘法器变为0.32 * pow(2,32)〜= 1374389535 == 0x51EB851F

So the optimizer replaced your division by a multiplication using fixed-point math, taking advantage of a 32-bit multiply producing a 64-bit result into edx:eax. Back-of-the-envelope: n / 100 == n * 0.32 / 32 == n * (0.32 * pow(2,32)) / 32 / pow(2,32). Those divisions are very cheap, just a right-shift. And the multiplier becomes 0.32 * pow(2,32) ~= 1374389535 == 0x51EB851F

这篇关于理解MSVS C ++编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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