【问题标题】:Preprocessor flags vs. (e.g.) boolean flags预处理器标志与(例如)布尔标志
【发布时间】:2013-02-08 18:39:21
【问题描述】:

我正在熟悉科学的流体动力学代码。代码几乎总是使用预处理器指令,例如

#ifdef PARTICLES
    int nghost = 5
#else
    int nghost = 4
#endif

而不是更简单的 C 标志,例如,

int nghost = 4;
if( particlesFlag ) { nghost = 5; }

预处理器标志的缺点是(在此框架中)它需要在每次构建之前为每个问题设置进行配置(创建头文件),而使用 c 代码标志只需要重新编译。

这种方法有什么优势?

似乎任何效率的提高都非常小——尤其是因为这段代码(例如)只在程序初始化时运行一次,而所有真正的工作都发生在不同处理器的循环中,等等

【问题讨论】:

    标签: optimization coding-style preprocessor flags


    【解决方案1】:

    假设我有数千个使用 nghost 的 API。如果已经定义了 PARTICLES,则所有这些变量将在预处理期间被 5 else by 4 替换。

    你说的是单个实例,一个大项目是预处理很有用的地方。

    考虑一下。

    int x() { int a = nghost *5; }
    int ab() { return (nghost+10); }
    

    每次,如果使用,它的运行时间消耗

    int x() { 
    int a;
    int nghost = 4;
    if( particlesFlag ) { nghost = 5;}
    a=nghost*5;
    }
    
    
    int ab() { 
    int nghost = 4;
    if( particlesFlag ) { nghost = 5;}
    return (nghost+10); 
    

    }

    等等。

    还要考虑一下。

    假设

    #ifdef PARTICLES
    int nghost = 5
    int aghost = 5
    int bghost = 5
    int cghost = 5
    int dghost = 5
    int eghost = 5
    int fghost = 5
    #else
    int nghost = 4
    int aghost = 4
    int bghost = 4
    int cghost = 4
    int dghost = 4
    int eghost = 4
    int fghost = 4
    #endif
    

    【讨论】:

    • 感谢您的回复,但我有点困惑。在我给出的示例中,您可以将第一个转换为int nghost = 5(如果定义了PARTICLES)。所以这两个例子的唯一区别就是在代码执行过程中是否执行if...else...语句,对吧?
    • 当你说 if 和 else 时,它​​是在运行时,这就是你的程序应该很快的地方。 .预处理是在您进行编译时,甚至在编译之前实时进行。 .
    • 好吧,我明白了。我不明白为什么 accessing 变量 (nghost) 在这两种情况下是不同的。 IE。如果 nghost 是通过预处理器与在代码中定义的,int x() { int a = nghost *5; } 会有什么不同?
    • 运行时与编译时不同。 .请参阅我的答案以获取更多说明。每次,您都必须进行 if 检查,而如果在预处理中,它只是一个算术。 .like 5*5 或 4*5
    • nghost 只定义一次。无论上述两种实现方式,nghost 的每种用法都应该相同,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    相关资源
    最近更新 更多