Saturday, 15 January 2011

algorithm - Which is more efficient. if(a-b >0) or if (a > b) -



algorithm - Which is more efficient. if(a-b >0) or if (a > b) -

this might simple question.

i want know of 2 statements take less time executed.

if ( - b > 0 ) or if ( > b )

in 1st case, difference has computed , has compared 0, while in 2nd case, , b compared directly.

thanks.

as keith thompson points out, 2 not same. if a , b unsigned, example, a-b non-negative, making statement equivalent if(a != b).

anyway, did unrealistic test:

int main() { volatile int a, b; if(a-b>=0) printf("a"); if(a>b) printf("b"); homecoming 0; }

compile -o3. here's disassembly:

pushq %rbp ltmp2: .cfi_def_cfa_offset 16 ltmp3: .cfi_offset %rbp, -16 movq %rsp, %rbp ltmp4: .cfi_def_cfa_register %rbp subq $16, %rsp movl -4(%rbp), %eax subl -8(%rbp), %eax testl %eax, %eax jle lbb0_2 ## bb#1: movl $97, %edi callq _putchar lbb0_2: movl -4(%rbp), %eax cmpl -8(%rbp), %eax jle lbb0_4 ## bb#3: movl $98, %edi callq _putchar lbb0_4: xorl %eax, %eax addq $16, %rsp popq %rbp ret

at -o3, a-b>0 still using 1 instruction.

even if compile arm compiler, there's instruction:

force {lr} sub sp, sp, #12 ldr r2, [sp, #0] ldr r3, [sp, #4] subs r3, r2, r3 cmp r3, #0 ble .l2 movs r0, #97 bl putchar(plt) .l2: ldr r2, [sp, #0] ldr r3, [sp, #4] cmp r2, r3 ble .l3 movs r0, #98 bl putchar(plt) .l3: movs r0, #0 add together sp, sp, #12 pop {pc}

note (1) volatile unrealistic unless dealing e.g. hardware registers or thread-shared memory, , (2) difference in practice not measurable.

because 2 have different semantics in cases, write correct. worry optimization later!

algorithm performance

No comments:

Post a Comment