转自聊聊这个与代码优化有关的选择题 (某公司实习生招聘笔试试题)
程序的完整编译过程分为是:预处理,编译,汇编等,如下关于编译阶段的编译优化的说法中不正确的是()
A、死代码删除指的是编译过程直接抛弃掉被注释的代码;
B、函数内联可以避免函数调用中压栈和退栈的开销
C、For循环的循环控制变量通常很适合调度到寄存器访问
D、强度削弱是指执行时间较短的指令等价的替代执行时间较长的指令
A. 了解编译原理的同学都清楚, 死代码主要是指1. 执行不到的代码. 2. 执行得到, 但没有任何作用的代码。 总而言之一句话: 死代码就是“不产生实际作用”的代码(而不是上面A选项说的那样的)。 举个例子:
- #include <iostream>
- using namespace std;
- int main()
- {
- int a = 1; // 死代码
- int b = 2;
- cout << b << endl;
- // 死代码
- if(0)
- {
- cout << "hello world" << endl;
- }
- // 死代码
- #if 0
- cout << "hello world" << endl;
- #endif
- return 0;
- cout << "hello world" << endl; // 死代码
- }
#include <iostream>
using namespace std;
int main()
{
int a = 1; // 死代码
int b = 2;
cout << b << endl;
// 死代码
if(0)
{
cout << "hello world" << endl;
}
// 死代码
#if 0
cout << "hello world" << endl;
#endif
return 0;
cout << "hello world" << endl; // 死代码
}
B. C++中的inline函数, 在当地展开。 C/C++中的宏也是展开。 都没有什么调用压栈的过程。不过inline和宏又是有差别的, inline在运行时可调式, 宏则死板展开。 而且宏会有边际副作用, 不好。 总之, inline既高效, 又安全。 为什么呢? 咱吃点小菜就明白了:
- #include <iostream>
- using namespace std;
- // 比较宏和inline
- #define SQU(x) ((x) * (x))
- inline squ(int x)
- {
- return x * x;
- }
- int main()
- {
- int a = 3;
- cout << SQU(++a) << endl; // 25
- int b = 3;
- cout << squ(++b) << endl; // 16
- return 0;
- }
#include <iostream>
using namespace std;
// 比较宏和inline
#define SQU(x) ((x) * (x))
inline squ(int x)
{
return x * x;
}
int main()
{
int a = 3;
cout << SQU(++a) << endl; // 25
int b = 3;
cout << squ(++b) << endl; // 16
return 0;
}
C. 我们知道, cpu要内存中取i需要一定的时间, 还不如直接在自己身体中的寄存器中取。 实际上, 很多编译器默认做了此类优化, 所以下面的代码在实际开发中并不常见。
- #include <iostream>
- using namespace std;
- int main()
- {
- register int i = 0;
- for(i = 0; i < 100; i++)
- {
- cout << i << endl;
- }
- return 0;
- }
#include <iostream>
using namespace std;
int main()
{
register int i = 0;
for(i = 0; i < 100; i++)
{
cout << i << endl;
}
return 0;
}
D. 强度削弱,很好理解, 就是不让强度那么大, 说白了, 就是用执行时间较短的操作(指令)去地代替一个耗时操作, 如:
- #include <iostream>
- using namespace std;
- int main()
- {
- int a1 = 5;
- int b1 = 17;
- int c1 = a1 * b1;
- cout << c1 << endl;
- // 强度削弱
- int a2 = 5;
- int b2 = a2 << 4;
- int c2 = a2 + b2;
- cout << c2 << endl;
- return 0;
- }
#include <iostream>
using namespace std;
int main()
{
int a1 = 5;
int b1 = 17;
int c1 = a1 * b1;
cout << c1 << endl;
// 强度削弱
int a2 = 5;
int b2 = a2 << 4;
int c2 = a2 + b2;
cout << c2 << endl;
return 0;
}
再如:
- #include <iostream>
- using namespace std;
- int main()
- {
- int a1 = 24933;
- int b1 = 128;
- int c1 = a1 % b1;
- cout << c1 << endl;
- // 强度削弱
- int a2 = 24933;
- int b2 = 128; //容易证明 x%(2^n) = x&(2^n - 1), 其中^乘方
- int c2 = a2 & 127;
- cout << c2 << endl;
- return 0;
- }
#include <iostream>
using namespace std;
int main()
{
int a1 = 24933;
int b1 = 128;
int c1 = a1 % b1;
cout << c1 << endl;
// 强度削弱
int a2 = 24933;
int b2 = 128; //容易证明 x%(2^n) = x&(2^n - 1), 其中^乘方
int c2 = a2 & 127;
cout << c2 << endl;
return 0;
}
慢慢积累。