代码优化--死代码

程序的完整编译过程分为是:预处理,编译,汇编等,如下关于编译阶段的编译优化的说法中不正确的是()

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; 	// 死代码
}

B.  C++中的inline函数, 在当地展开。 C/C++中的宏也是展开。 都没有什么调用压栈的过程。不过inline和宏又是有差别的, inline在运行时可调式, 宏则死板展开。 而且宏会有边际副作用, 不好。 总之, inline既高效, 又安全。 为什么呢? 咱吃点小菜就明白了:

#include <iostream> 
using namespace std; 
  
// 比较宏和inline  
#define SQU(x) ((x) * (x))    
 
inline int 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; 
} 
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 = 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; 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值