Chinaunix首页 | 论坛 | 博客
  • 博客访问: 619461
  • 博文数量: 233
  • 博客积分: 2221
  • 博客等级: 大尉
  • 技术积分: 3184
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-16 14:01
个人简介

瓜瓜派的瓜瓜

文章分类

全部博文(233)

文章存档

2013年(28)

2012年(197)

2011年(8)

分类: C/C++

2012-01-09 17:00:42

读BrianW. Kernighan和Dennis M. Ritchie的英文版《C程序设计语言》,第18页有这么一句话"You couldinstead write nc = nc+1 but ++nc is more concise and often moreefficient."

为什么说"一般情况下++nc比nc=nc+1更高效"?

这让我回想起美国CSE学校计算机系乐团的那首"Coding in C"里有一句歌词"save some time with plus plus i"

为什么说"++i可以save some time"?

带着这个疑问,回想起以前学GNU/Linux下的汇编,看过将C程序反汇编分析程序效率的例子。决定自己也动手做个实验。

打开GNU小本,用emacs编写main.c和Makefile两个文件如下:

~/temp $ ls
Makefile  main.c
~/temp $ make
gcc main.c
gcc -S main.c
~/temp $ ls
Makefile  a.out  main.c  main.s
~/temp $ cat main.c
int
main(void)
{
  int i=0;
  asm("#begin");        /* 用于反汇编成汇编程序后的识别标记 */
  ++i;
  asm("#middle");
  i=i+1;
  asm("#end");
  return 0;
}
~/temp $ cat Makefile 
all:
    gcc main.c
    gcc -S main.c

clean:
    rm -f *~ a.out main.s
~/temp $ cat main.s
    .file    "main.c"
    .text
.globl main
    .type    main, @function
main:
    leal    4(%esp), %ecx
    andl    $-16, %esp
    pushl    -4(%ecx)
    pushl    %ebp
    movl    %esp, %ebp
    pushl    %ecx
    subl    $16, %esp
    movl    $0, -8(%ebp)
#APP
# 5 "main.c" 1
    #begin
# 0 "" 2
#NO_APP
    addl    $1, -8(%ebp)
#APP
# 7 "main.c" 1
    #middle
# 0 "" 2
#NO_APP
    addl    $1, -8(%ebp)
#APP
# 9 "main.c" 1
    #end
# 0 "" 2
#NO_APP
    movl    $0, %eax
    addl    $16, %esp
    popl    %ecx
    popl    %ebp
    leal    -4(%ecx), %esp
    ret
    .size    main, .-main
    .ident    "GCC: (Debian 4.3.2-1.1) 4.3.2"
    .section    .note.GNU-stack,"",@progbits
~/temp $


由上可知,单独地用++i和i=i+1的效率是一样的,都对应于同一汇编语句
addl    $1, -8(%ebp)

我表错情了......

++i一般比i=i+1高效应该是指
1. ++i比i=i+1少打几个字
2. 组合使用时,如
if (++num >= SAVED_LOG_LINES)
   ++end;
用++i的形式,表达紧凑(高效)很多

就当多一次小丑吧:)

 


参考资源
1. coding in c + 计算机系系列歌曲

2. Professional_Assembly_Language.pdf GNU/Linux汇编
阅读(964) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~