c++ - 模板和内联优化乘法

标签 c++ templates optimization inline-assembly

我不明白我遇到的这个例子:

int Multiply(int x, int m){
    return x * m;}

template<int m>
int MultiplyBy(int x){
    return x * m;}

int a,b;
a = Multiply(10,8);
b = MultiplyBy<8>(10);

In the above example the template function is faster than the simple function because the compiler knows that it can multiply by a power of 2 by using a shift operation. x*8 is replaced by x << , which is faster. In the case of the simple function, the compiler doesnt know the value of m and therefore cannot do the optimization unless the function can be inlined.

据我了解,模板可以优化的原因是因为编译器在编译时知道参数 (8) 的值,而简单函数直到运行时才知道 x(或 m)的值-时间。那么内联简单函数将如何改变这一事实呢?内联不提供参数值的任何运行时知识??

最佳答案

Inlining doesn't provide any run-time knowledge of the argument value??

内联本身没有。但是,由于第二个参数是编译时常量,编译器可以将该常量传播到内联函数中。

由于第一个参数也是一个编译时常量,所以整个

a = Multiply(10,8);

可以替换为

a = 80;

事实上,当我打开优化时,这正是我的编译器 (gcc 4.7.2) 所做的。

关于c++ - 模板和内联优化乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532209/

相关文章:

c++ - 为什么在以下代码中每次输出后我都会得到 32767?

c++ - ASSERT-C++ 的编译器错误

c++ - 函数模板 - 编译器在使用相同类型调用时选择具有不同参数类型的函数

c++ - 随机数数组的优化提示

c++ - block 内存的简单自定义分配器?

c++ - 验证在C++中创建多个文件夹和文件的正确方法

c++ - 使用负浮点值计算比例

c++ - 使用 std::tuple 传递 c++ 模板包是否有任何原因

c++ - 模板模板总特化

sql - 如何优化 BINARY(N) 的 SQL 查询?