Optimizing Program Performance-- Capability and limitation of Optimizing Compilers

来源:互联网 发布:snow软件 编辑:程序博客网 时间:2024/05/09 09:27

编译器优化代码的时候, 并不是所有的代码都可以优化的。

 

有下面两种情况,不能优化。


1. Memory aliasing

2. function call

 

 

例子1

1 void twiddle1(int *xp, int *yp)
2 {
3     *xp += *yp;
4     *xp += *yp;
5 }
6
7 void twiddle2(int *xp, int *yp)
8 {
9     *xp += 2* *yp;
10 }

 

 

粗看这两个函数执行的结果是一样的。They both add twice the value stored at the
location designated by pointer yp to that designated by pointer xp.

但是当传入的参数xp == yp的时候,

twiddle1执行的是

3 *xp += *xp; /* Double value at xp */
4 *xp += *xp; /* Double value at xp */

 

而twiddle2执行的是

9 *xp += 2* *xp; /* Triple value at xp */

 

这样就不一样了,这就是 memory aliasing

 

 

例子2

 

1 int f(int);
2
3 int func1(x)
4 {
5     return f(x) + f(x) + f(x) + f(x);
6 }
7
8 int func2(x)
9 {
10     return 4*f(x);
11 }

 

一般而言,这两个函数都是计算了4倍的f(x).

但是如果f(x)定义如下:

1 int counter = 0;
2
3 int f(int x)
4 {
5       return counter++;
6 }
7

 

这样,两个函数的结果就不一样了:

In particular, a call to func1 would return 0+1+2+3 =
6, whereas a call to func2 would return 4  0 = 0, assuming both started with global variable counter
set to 0.

 

这个就是 function call.

 

 

原创粉丝点击