随便写一段代码 论证一下简单代码的优化(用宏有什么收获?)
程序代码:
#include <stdio.h> int inc(int a) { return (a+1); } int main(void) { int x = 521; int i = 0; printf("%d\n", x); for (i = 0; i < 1314000; i++) { x = inc(x); } printf("%d\n", x); return 0; }
gcc -Wall a.c
Compilation finished at Sat Jan 19 13:46:01
程序代码:
0x004013c7 <main+14>: mov DWORD PTR [esp+0x1c],0x209 0x004013cf <main+22>: mov DWORD PTR [esp+0x18],0x0 0x004013d7 <main+30>: mov eax,DWORD PTR [esp+0x1c] 0x004013db <main+34>: mov DWORD PTR [esp+0x4],eax 0x004013df <main+38>: mov DWORD PTR [esp],0x403064 0x004013e6 <main+45>: call 0x401c50 <printf> 0x004013eb <main+50>: mov DWORD PTR [esp+0x18],0x0 0x004013f3 <main+58>: jmp 0x401409 <main+80> 0x004013f5 <main+60>: mov eax,DWORD PTR [esp+0x1c] 0x004013f9 <main+64>: mov DWORD PTR [esp],eax 0x004013fc <main+67>: call 0x4013b0 <inc> 0x00401401 <main+72>: mov DWORD PTR [esp+0x1c],eax 0x00401405 <main+76>: inc DWORD PTR [esp+0x18] 0x00401409 <main+80>: cmp DWORD PTR [esp+0x18],0x140ccf 0x00401411 <main+88>: jle 0x4013f5 <main+60> 0x00401413 <main+90>: mov eax,DWORD PTR [esp+0x1c] 0x00401417 <main+94>: mov DWORD PTR [esp+0x4],eax 0x0040141b <main+98>: mov DWORD PTR [esp],0x403064 0x00401422 <main+105>: call 0x401c50 <printf>
gcc -Wall a.c -O2
Compilation finished at Sat Jan 19 13:52:30
循环啦 函数调用啦 全部优化掉了 最终的结果就是两个输出 请问 这里如果换成宏 能有什么收获?
程序代码:
0x00401c86 <main+14>: mov DWORD PTR [esp+0x4],0x209 0x00401c8e <main+22>: mov DWORD PTR [esp],0x403064 0x00401c95 <main+29>: call 0x401be0 <printf> 0x00401c9a <main+34>: mov DWORD PTR [esp+0x4],0x140ed9 0x00401ca2 <main+42>: mov DWORD PTR [esp],0x403064 0x00401ca9 <main+49>: call 0x401be0 <printf>
结论
1 gcc对于这种代码的优化是【杀鸡焉用牛刀】
2 用函数调用在开编译优化的情况下没有性能损失
3 gcc真是好东西啊
[ 本帖最后由 zklhp 于 2013-1-19 13:57 编辑 ]