2011-06-11 79 views
3

我正在比较两个C文件的两个汇编形式,一个带有优化标志(-O2),另一个没有。用优化标志编译C

我的问题是:

这是为什么在优化的程序集版本,编译器把主要功能的所有辅助功能后,而辅助功能是第一位在原汇编代码。这在效率方面意味着什么?有人可以详细说明吗?

这是原始的C文件。谢谢!

// Based on a source file found in a beginner's discussion on multidimensional arrays here: 
// http://www.dreamincode.net/forums/topic/71617-3d-arrays/ 

#include <stdio.h> 
#include <string.h> 

int validColor(char *str); 
int mathProblem(char *str); 

// 1) Asks from six 'theoretical' different users one of two questions, 
// allowing only three answers for each. 
// 2) Stores the response into a multidimensional array 

int main(void) 
{ 
     char myArray[ 6 ][ 3 ][ 20 ]; /* Six users, three questions, and up to 19 characters per answer 
(strings are '\0' terminated), though no "true" answer is that long */ 
     int i, valid; 

/* User instructions */ 
     for(i = 0; i < 6; i++) 
     { 
if (i % 2 == 0) 
{ 
valid = 0; 
while(valid == 0) 
{ 
       printf("Enter your favorite color : "); 

       fgets(myArray[ i ][ 0 ], 20, stdin); /* Get answer to first question */ 

if(myArray[ i ][ 0 ][ 0 ] == '\n') /* If the user just presses enter, move to next question */ 
break; /* Jump out of while loop */ 

valid = validColor(myArray [i ][ 0 ]); /* Call function to validate answer */ 
} 
} 
if (i % 2 == 1) 
{ 
valid = 0; 
while(valid == 0) 
         { 
           printf("The roots of (x - 4)^2 : "); 

           fgets(myArray[ i ][ 0 ], 20, stdin); /* Get answer to second question */ 

           if(myArray[ i ][ 0 ][ 0 ] == '\n') /* If the user just presses enter, move to next question */ 
             break; /* Jump out of while loop */ 

           valid = mathProblem(myArray[ i ][ 0 ]); /* Call function to validate answer */ 
         } 
} 
     } 

     return 0; 
} 

int validColor(char *str) 
{ 
if(strcmp(str, "Black\n") == 0) 
return 1; 
if(strcmp(str, "Red\n") == 0) 
return 1; 
if(strcmp(str, "Blue\n") == 0) 
return 1; 

return 0; /* If no match above, answer is not valid */ 
} 

int mathProblem(char *str) 
{ 
if (atoi(str) == 2) /* Function call for analysis purposes */ 
return 1; 
if (strcmp(str, "-2\n") == 0) 
return 1; 
if (strcmp(str, "+2\n") == 0) 
return 1; 

return 0; /* If no match above, answer is not valid */ 
} 
+0

为了充分披露,您使用哪种编译器? – 2011-06-11 00:48:03

+0

我正在使用gcc -S – Tom 2011-06-11 00:58:15

+5

“所有辅助函数之后的主函数”和“辅助函数优先”之间的区别是什么? – 2011-06-11 04:10:50

回答

3

它在效率方面没有实质性差异。

4

为了提高效率,约翰是完全正确的。毕竟在一个目标文件中编译后,函数只是符号表中的条目,顺序无关紧要。

对于你的问题,为什么这个命令会出现这样:

  • 没有优化的时候,所有的呼叫, 功能是函数的 地址只是引用。编译器 然后可以按照它遇到函数的定义的顺序容易地发出目标代码 。
  • 优化时,编译器用内联代码替代 (至少潜在地)所有调用到 定义的小函数。 所以当他遇到这个函数时,他一般不会发出代码 ,但是 必须等到他最终看到 所有被调用的函数 的声明。发射顺序因此是 ,就像调用图的逆向线性排列 。
+0

如果有的话,它也可能适得其反。如果之前有足够的代码,指令更有可能最终分散在不同的缓存行中。 – 2011-06-11 09:26:20

+0

简而言之,它取决于编译器生成代码的顺序,没有直接影响生成代码的效率。 – Clifford 2011-06-11 09:27:53