c语言常量折叠,为什么C ++编译器的常数折叠效果更好?

强制编译器通过0和1优化乘法的一种方法是手动展开循环。 为了简单起见,我们使用

#include

#include

constexpr std::size_t n = 12;

using Array = std::array;

然后,我们可以使用折叠表达式(或递归(如果不可用,则递归))实现一个简单的for (std::size_t i = 0; i < n; ++i) ...函数:

template<:size_t... is>

double dot(const Array& x, const Array& y, std::index_sequence)

{

return ((x[is] * y[is]) + ...);

}

double dot(const Array& x, const Array& y)

{

return dot(x, y, std::make_index_sequence{});

}

现在让我们来看一下您的功能

double test(const Array& b)

{

const Array a{1}; // = {1, 0, ...}

return dot(a, b);

}

gcc 8.2使用for (std::size_t i = 0; i < n; ++i) ... gcc产生:

test(std::array const&):

movsd xmm0, QWORD PTR [rdi]

ret

clang 6.0.0遵循相同的原则:

test(std::array const&): # @test(std::array const&)

movsd xmm0, qword ptr [rdi] # xmm0 = mem[0],zero

ret

例如,对于

double test(const Array& b)

{

const Array a{1, 1}; // = {1, 1, 0...}

return dot(a, b);

}

我们得到

test(std::array const&):

movsd xmm0, QWORD PTR [rdi]

addsd xmm0, QWORD PTR [rdi+8]

ret

加成。 Clang展开了for (std::size_t i = 0; i < n; ++i) ...循环,没有所有这些折叠表达式的技巧,gcc却没有,并且需要一些帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值