新手想问几个问题(100分全给了)
问题1:
while( --n > 0) {} ;对于以上的四种循环,哪种效率更高呢?我看过有些人通过循环多次的运行时间来判断各语句的效率,那么在mingw或VC的测试代码该怎么写呢?(该用什么函数?)另外,有些人通过查看汇编程序来判断效率,但我没学过汇编,有没有简单办法能看懂汇编语句来够判断各语句的效率?
while (n-- > 0) {} ;
for ( ; ; --n) {} ;
for ( ; ; n--) {} ;
#include "time.h"
#include "stdio.h"
#include "conio.h"
void main()
{
time_t start,end;
int i;
start=time(NULL);
for(i=0;i<30000;i++)
printf("\1\1\1\1\1\1\1\1\1\1\n");
end=time(NULL);
printf("\1: The different is %6.3f\n",difftime(end,start));
getch();
}
d: 8d 76 00 lea 0x0(%esi),%esi
10: 0f af c2 imul %edx,%eax
13: 83 ea 01 sub $0x1,%edx
16: 85 d2 test %edx,%edx
18: 7f f6 jg 10 <fun1+0x10>
1a: 5d pop %ebp
1b: c3 ret
int fun2(int n)
{
int p;
while(n-->0)
{
p = p*n;
}
return p;
}
00000000 <fun2>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 55 08 mov 0x8(%ebp),%edx
6: 85 d2 test %edx,%edx
8: 7e 11 jle 1b <fun+0x1b>
a: 83 ea 01 sub $0x1,%edx
d: 8d 76 00 lea 0x0(%esi),%esi
10: 0f af c2 imul %edx,%eax
13: 83 ea 01 sub $0x1,%edx
16: 83 fa ff cmp $0xffffffff,%edx
19: 75 f5 jne 10 <fun2+0x10>
1b: 5d pop %ebp
1c: c3 ret
编译选项均采用:gcc -c -O2 fun1.c
从汇编代码看,while循环中只差一个指令test %edx,%edx和cmp $0xffffffff,%edx,所以效率应该是一样的。
int fun1(int n)
{
int p;
for(; n>0; --n)
{
p = p*n;
}
return p;
}
00000000 <fun1>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 55 08 mov 0x8(%ebp),%edx
6: 85 d2 test %edx,%edx
8: 7e 10 jle 1a <fun1+0x1a>
a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
10: 0f af c2 imul %edx,%eax
13: 83 ea 01 sub $0x1,%edx
16: 85 d2 test %edx,%edx
18: 7f f6 jg 10 <fun1+0x10>
1a: 5d pop %ebp
1b: c3 ret
int fun2(int n)
{
int p;
for(; n>0; n--)
{
p = p*n;
}
return p;
}
00000000 <fun2>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 55 08 mov 0x8(%ebp),%edx
6: 85 d2 test %edx,%edx
8: 7e 10 jle 1a <fun1+0x1a>
a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
10: 0f af c2 imul %edx,%eax
13: 83 ea 01 sub $0x1,%edx
16: 85 d2 test %edx,%edx
18: 7f f6 jg 10 <fun2+0x10>
1a: 5d pop %ebp
1b: c3 ret
可以看到for的汇编代码是一样的,所以没差别