【问题标题】:Do modern compilers optimize multiplication by 1 and -1现代编译器是否优化乘法 1 和 -1
【发布时间】:2014-04-12 08:15:46
【问题描述】:

如果我写

template<int sign>
inline int add_sign(int x) {
    return sign * x;
}

template int add_sign<-1>(int x);
template int add_sign<1>(int x);

大多数 C++ 编译器是否足够聪明,可以将乘法 1 或 -1 优化为更快的运算(无运算或取反)?

【问题讨论】:

  • 为什么不检查编译器的汇编输出?很可能会回答您的问题。
  • 我不知道怎么做。我该怎么做?
  • 第一步是搜索“[你的编译器]生成程序集”
  • 定义“现代”。第一个 Fortran 编译器是在 1957 年这样做的。

标签: c++ templates compiler-construction compiler-optimization sign


【解决方案1】:

对于g++,使用g++ -S Foo.cc查看汇编,判断模板是否优化。对于clang,请查看this question。对于 Visual Studio,请查看 this question

【讨论】:

    【解决方案2】:

    是的。这是称为算术局部优化的一类简单优化的一部分。例如1 * x可以静态简化为x,同样-1 * x可以简化为-x。生产编译器都执行此操作,以及更复杂的优化。

    【讨论】:

      【解决方案3】:

      虽然在这种情况下编译器会为您进行优化,但在更复杂的情况下,可能需要为不同的模板参数编写不同的优化代码变体。因此,您可以使用模板专业化来做到这一点:

      template<int sign>
      inline int add_sign(int x);
      
      template<>
      inline int add_sign<-1>(int x) {
          return -x;
      }
      
      template<>
      inline int add_sign<1>(int x) {
          return x;
      }
      

      使用这种完全专业化的功能,您无需为其编写显式实例化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-25
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        相关资源
        最近更新 更多