[英]Understanding of MSVS C++ compiler optimizations
I do not understand what is happening in this code. 我不明白这段代码中发生了什么。 The C code is: 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;
}
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? 我期望得到的程序集将是一些简单的移位和添加/子操作,但是有一些神奇的常量,如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
Processors are not very good at dividing, an idiv can take between 11 and 18 cycles. 处理器不是很擅长划分,一个idiv可能需要11到18个周期。 As opposed to shifts and multiplies, they usually only take a single cycle. 与轮班和倍数相反,它们通常只需要一个周期。
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. 因此,优化器通过使用定点数学运算的乘法替换了除法,利用32位乘法将64位结果生成到edx:eax中。 Back-of-the-envelope: n / 100 == n * 0.32 / 32 == n * (0.32 * pow(2,32)) / 32 / pow(2,32). 背面: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 乘数变为0.32 * pow(2,32)〜= 1374389535 == 0x51EB851F
51EB851Fh seems to be the magic number for divider for dividing through 100 51EB851Fh似乎是除以100的分频器的神奇数字
Source: http://masm32.com/board/index.php?topic=1906.0 Reply #2 来源: http : //masm32.com/board/index.php? topic = 1906.0回复#2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.