2012-06-23 64 views
0

我有我的计划:优化程序(C)

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

int main (int argc, char *argv[]) 
{ 
    int r, line = 0, found = 0; 
    float temp, t_tot = 0; 
    char loc[32]; 


    FILE *fp; 

    fp = fopen(argv[1], "r"); 

    if (fp == NULL) 
    { 
     printf ("Error opening the file\n\n'"); 
     exit(EXIT_FAILURE); 
    } 

    if (argc == 3) 
    { 
     while ((r = fscanf(fp, "%f %s\n", &temp, loc)) != EOF) 
     { 
      line++; 

      if (r == 2) 
      { 
       if(strcmp(argv[2], loc) == 0) 
       { 
        t_tot += temp; 
        found++; 
       } 
      } 
      else 
       printf ("Error, line %d in wrong format!\n\n", line); 
     } 

     printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot/found)); 
    } 

    fclose(fp) 

    return 0; 

} 

程序需要读取所有的行,发现我在写的argv城[2]。它会告诉我该城市的平均气温,通知我文件中的某一行是否格式错误。

我想知道如何“优化”这个代码,以便更有效率,并以更紧凑的方式编写相同的东西。我是一名学生,所有的建议都被接受。

+3

这会更适合于http://codereview.stackexchange.com。 –

+0

在我看来,结构尚好。 –

+0

检查'main'顶部的'argc'是一种常见的做法,而不是返回循环中的检查。 – dasblinkenlight

回答

0

有关更改

if (r == 2) 
{ 
    if(strcmp(argv[2], loc) == 0) 
    { 
     t_tot += temp; 
     found++; 
    } 
} else { 
    printf ("Error, line %d in wrong format!\n\n", line); 
} 

成这样了,为了避免嵌套if块什么:

if (r == 2 && strcmp(argv[2], loc) == 0) { 
    t_tot += temp; 
    found++; 
} else if (r != 2) { 
    printf ("Error, line %d in wrong format!\n\n", line); 
} 

看起来比较清爽了很多给我!

+3

除了你现在[重复你自己](http://en.wikipedia.org/wiki/) DRY)... –

+0

是的,但我认为这是值得的,避免嵌套块。 – v1Axvw

+0

为什么这是一个改进?这两个甚至编译成不同的汇编器? – Kos

3

获得一个剖析器像GNU GProf或AMD CodeAnalyst。

又见What's the best free C++ profiler for Windows?

然后用最高的优化编译程序,并尝试检查哪些部件往往要花费很多时间。

通常不需要优化探查器。


虽然我们在这,你的程序并没有真正做到这一点就需要大量时间任何计算,其性能可能会受到I/O(我猜测)的约束。

您可以做的另一件事,而不是优化,是使其安全和正确 - 例如,以便它不会崩溃,如果输入文件中的字符串超过32个字符。

1

您还可以使用编译器优化选项优化目标代码。对于gcc,只需添加-O3(或-O1-O2,取决于优化级别)参数。