x86 gcc 里绝对值优化求法

来源:互联网 发布:淘宝美工店铺装修教程 编辑:程序博客网 时间:2024/06/05 17:29

先看代码:

#test.c 

# 条件表达式

int abs0(int v)

{

return v > 0 ? v : - v ; 

}

#补码求法

int abs1(int v)

{

int c = v >> 31;

return (v ^ c) - c;

}


以上绝对值求法哪个快?

看下汇编代码:

#gcc -E  test.c -o test.i 

#gcc -S test.i -O2 -o test.s 

#test.c 

  1     .file   "test.c"
  2     .text
  3     .p2align 4,,15
  4     .globl  abs0
  5     .type   abs0, @function
  6 abs0:
  7 .LFB0:
  8     .cfi_startproc
  9     movl    %edi, %edx
 10     movl    %edi, %eax
 11     sarl    $31, %edx
 12     xorl    %edx, %eax
 13     subl    %edx, %eax
 14     ret
 15     .cfi_endproc
 16 .LFE0:
 17     .size   abs0, .-abs0
 18     .p2align 4,,15
 19     .globl  abs1
 20     .type   abs1, @function
 21 abs1:
 22 .LFB1:
 23     .cfi_startproc
 24     movl    %edi, %edx
 25     movl    %edi, %eax
 26     sarl    $31, %edx
 27     xorl    %edx, %eax
 28     subl    %edx, %eax
 29     ret
 30     .cfi_endproc
 31 .LFE1:
 32     .size   abs1, .-abs1
 33     .ident  "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4"
 34     .section    .note.GNU-stack,"",@progbits
~                                                      


发现gcc 都给优化成补码求法了! 在此记录一下。 



0 0
原创粉丝点击