1

I have aliases for radians and degrees that use float as the storage type.

When I convert between these two units I see the assembly promote the values to doubles and then back to floats when doing conversions.

Q: How can I make sure that all operations and conversions stay in floats?

My Code:

using radians_f = boost::units::quantity<boost::units::si::plane_angle, float>;
using degrees_f = boost::units::quantity<boost::units::degree::plane_angle, float>;

degrees_f to_degrees(const radians_f& angle) { return static_cast<degrees_f>(angle); }
radians_f to_radians(const degrees_f& angle) { return static_cast<radians_f>(angle); }

From compiler explorer I see the following assembly instructions: https://godbolt.org/z/Gnjr54dn6

  • cvtss2sd - Converts a single-precision floating-point value in the “convert-from” source operand to a double-precision floating-point value in the destination operand.

  • mulsd - Multiplies the low double-precision floating-point value in the second source operand by the low double-precision floating-point value in the first source operand.

  • cvtsd2ss - Converts a double-precision floating-point value in the “convert-from” source operand to a single-precision floating-point value

PS: I would not be surprised if I have defined my aliases or/and my conversion functions incorrectly.

4

1 回答 1

1

我找到了一个 hacky 解决方法(我确信可以通过让 Boost Units 计算每个弧度常数 57.x 度来“生产”它)以避免与 之间的转换double,但它确实突出了 Boost Units 导致另一个令人惊讶的开销:如果您float直接使用,甚至您自己的float.

演示:https ://godbolt.org/z/afPE7baxT

因此,尽管上面显示了一种(未完善的)强制计算保持为浮点数的方法,但如果您真正的问题是“我如何避免开销”,那么您离必杀技还有一点距离。

于 2021-11-23T10:46:36.543 回答