【问题标题】:Using const& type for relabeling variables使用 const 类型标记变量
【发布时间】:2013-01-18 21:07:18
【问题描述】:

我喜欢使用const& type T = LongVariableName 重新标记一小段代码中的变量,尤其是涉及公式的代码。

例如:

const double& x = VectorNorm;
double y = a*x*x*x + b*x*x + c*x + d;

我认为编译器应该足够聪明以优化这些引用变量。这几乎总是会发生吗?什么时候不呢?

【问题讨论】:

  • 顺便说一句,((a * x + b) * x + c) * x + d 可能比你的公式更快。
  • 另外,我会去掉引用,只写double x = VectorNorm;

标签: c++ variables reference names


【解决方案1】:

这取决于编译器和您设置的优化选项 - 不能保证它会或不会被优化掉。启用优化的现代编译器可能会将其优化掉,但更好的问题是:您应该关心吗?除非您处于每秒运行数千次的紧密循环中,否则不要担心。代码清晰通常比减少几个时钟周期更重要。

但无论如何,让我们来看看。我正在通过 MinGW 使用 gcc 4.7.2。我们将使用以下代码:

so.cpp:

#include <cstdio>

int main()
{
    float aReallyLongNameForAVariable = 4.2;
#ifdef SHORT_REF
    const float& x = aReallyLongNameForAVariable;
    float bar = x * x * x;
#else
    float bar = aReallyLongNameForAVariable * aReallyLongNameForAVariable * aReallyLongNameForAVariable;
#endif
    printf("bar is %f\n", bar);
    return 0;
}

没有“速记引用”,我们得到以下程序集:

g++ -S -masm=intel -o noref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+28], eax
fld DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fmul    DWORD PTR [esp+28]
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave

现在让我们使用参考:

g++ -DSHORT_REF -S -masm=intel -o ref.S so.cpp

call    ___main
mov eax, DWORD PTR LC0
mov DWORD PTR [esp+20], eax
lea eax, [esp+20]
mov DWORD PTR [esp+28], eax
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
mov eax, DWORD PTR [esp+28]
fld DWORD PTR [eax]
fmulp   st(1), st
fstp    DWORD PTR [esp+24]
fld DWORD PTR [esp+24]
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
mov eax, 0
leave

所以这是一个多一点的组装。但是当我们开启优化时会发生什么?

g++ -DSHORT_REF -O2 -S -masm=intel -o ref.S so.cpp
g++ -O2 -S -masm=intel -o noref.S so.cpp

两者都生成相同的程序集:

call    ___main
fld DWORD PTR LC0
fstp    QWORD PTR [esp+4]
mov DWORD PTR [esp], OFFSET FLAT:LC1
call    _printf
xor eax, eax
leave

所以你有它。现代编译器(至少是 gcc)优化了引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2022-01-08
    • 1970-01-01
    • 2012-01-14
    • 2021-04-19
    • 2015-12-07
    相关资源
    最近更新 更多