gpt4 book ai didi

c++ - 编译器优化 "constant propagation"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:49 43 4
gpt4 key购买 nike

摘自 Scott Meyers 的 Effective C++:

template<typename T, std::size_t n>
class SquareMatrix: private SquareMatrixBase<T> {

public:

SquareMatrix( )
: SquareMatrixBase<T>(n, 0),
pData(new T[n*n])
{
this->setDataPtr(pData.get());
}

...
private:

boost::scoped_array<T> pData;
};

Regardless of where the data is stored, the key result from a bloat point of view is that now many — maybe all — of SquareMatrix’s member functions can be simple inline calls to base class versions that are shared with all other matrices holding the same type of data, regardless of their size. At the same time, SquareMatrix objects of different sizes are distinct types, so even though, e.g., SquareMatrix<double, 5> and SquareMatrix<double, 1 0> objects use the same member functions in SquareMatrixBase<double>, there’s no chance of passing a SquareMatrix<double, 5> object to a function expecting a SquareMatrix<double, 1 0>. Nice, no?

Nice, yes, but not free. The versions of invert with the matrix sizes hardwired into them are likely to generate better code than the shared version where the size is passed as a function parameter or is stored in the object. For example, in the size-specific versions, the sizes would be compile-time constants, hence eligible for such optimizations as constant propagation, including their being folded into the generated instructions as immediate operands. That can’t be done in the size-independent version.

在上面最后一段的描述中,它被提到“因此有资格进行诸如持续传播之类的优化,包括将它们折叠到生成的指令作为立即操作数”。这个语句是什么意思?请要求解释这一点。

谢谢!

最佳答案

Constant Propagation 是留给编译器的非常简单(原则上)的优化。

size_t radius = 5;
size_t diameter = 2*radius;
float perimeter = diameter * 3.1416f;

这将由编译器通过传播常量来减少:

  • 注意 radius 的值是已知的
  • 执行2*radius的计算(这是常量折叠)
  • diameter 的值因此已知
  • 执行diameter * 3.1416f的计算
  • perimeter 的值因此已知

因此该程序等同于:

size_t radius = 5;
size_t diameter = 10;
float perimeter = 31.416f;

请注意,还有许多其他形式的优化,例如,如果现在不再需要 radiusdiameter,我们可以将它们删除,只保留 周长

关于c++ - 编译器优化 "constant propagation"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934926/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com