Find out max & min from two numbers without using If else?

I can find out the logic: Here

r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)

He says faster than doing

r = (x < y) ? x : y

Can someone explain a little more about this in order to figure this out with an example. How can it be faster?

+4
source share
5 answers

Discussing optimization without using specific equipment makes no sense. You really cannot say which one is faster without going into the details of a particular system. Feel free to make the expression that the first alternative is the fastest without any specific equipment, this is only a preliminary optimization.

xor , . , , , , (, if), . , - .., .

, , , .

, , CPU, , . , . .

+10

:

, , , [] , , r = (x < y)? x: y

:

(x < y) 0 1 , .

, , . ( ) .

+5

? ( ).

- "" , , . ALU ( , ) . , , .. , , .

: slloooowwwwwwww...

0

, . , x86 (, ). , .

; r = y ^ ((x ^ y) & -(x < y))
xor    edx,edx
cmp    ebx,eax
mov    ecx,eax
setl   dl
xor    ecx,ebx
neg    edx
and    edx,ecx  
xor    eax,edx  

; r = (x < y) ? x : y
cmp    ebx,eax  
cmovl  eax,ebx  

XOR , , 8 . x86 cmov . , ?: cmovl, 2 . ?: 4 , . , ?: , , , XOR.

, , .

0

-:

void func(int a,int b){
    int c = a - b;
    int k = (c >> 31) & 0x1;
    int max = a - k * c;
    int min = b + k * c;
    printf("max = %d\nmin = %d",max,min);
    }
0

Source: https://habr.com/ru/post/1546837/


All Articles