A clever substitution between division and arithmetic right shift

Source: Internet
Author: User
Tags arithmetic

On most machines, the division of integers is slow and requires more than 30 clock cycles, divided by the power of 2, and can be implemented with shift operations.

Code on first

#include "stdio.h"
int main ()
{
int x=-128;
int Y=X/4;
printf ("y=%d", y);
}


Attach the assembly code again

PUSHL%EBP
. Cfi_def_cfa_offset 8
. Cfi_offset 5,-8
MOVL%esp,%EBP
. Cfi_def_cfa_register 5
Andl $-16,%esp
Subl $32,%esp
Movl $-128, (%ESP)
MOVL (%ESP),%eax
Leal 3 (%EAX),%edx
Testl%eax,%eax//This step is to test whether the value of the%EAX register is 0. And the flag-position ZF and SF are set to 0 or 1.
Cmovs%edx,%eax//cmovs, sign 1, that is, when the number of symbols, the implementation of the MOV instructions. This is a conditional directive.
SARL,%eax//Because, for example, as in C, the right shift is the arithmetic right shift. So it's equivalent to the C-expression (x<0? (x+ (1<<k)-1): x) >>k, because the C code is divided by 4, then the right shift is 2 bits.
Movl%eax, (%ESP)
MOVL (%ESP),%eax
MOVL%eax, 4 (%ESP)
MOVL $. LC0, (%ESP)
Call printf

The main purpose of writing this note is two points.

First, on most machines, the division instruction is slower than the integer multiplication instruction and requires 30 clock cycles. The shift requires only 1 or several clock cycles. This saves a lot of time.

So some compilers will compile the division into a right-shift instruction.

Second, when the arithmetic right shifts, it is to be discussed in categories. Because in most programming languages, the right shift is the arithmetic right shift.

x/(2^k), if X is positive, then right shift, high 0, this is no problem;

When x is negative, move right, high 1, then the resulting number is rounded down (for example, the resulting theoretical value is-2.1, then the result is--3)

So to add 1 in the low, that is, in the K position 1. Change to C language

(x<0?) (x+ (1<<k)-1): x) >>k,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.