Skip to content

Commit

Permalink
Optimize fractional_part_rounding_thresholds
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Sep 22, 2023
1 parent 649f246 commit 06b2038
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3259,21 +3259,15 @@ FMT_CONSTEXPR20 void format_hexfloat(Float value, int precision,
format_hexfloat(static_cast<double>(value), precision, specs, buf);
}

FMT_CONSTEXPR inline uint32_t fractional_part_rounding_thresholds(int index) {
constexpr uint32_t fractional_part_rounding_thresholds(int index) {
// For checking rounding thresholds.
// The kth entry is chosen to be the smallest integer such that the
// upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k.
constexpr uint32_t thresholds[8] = {
2576980378U, // ceil(2^31 + 2^32/10^1)
2190433321U, // ceil(2^31 + 2^32/10^2)
2151778616U, // ceil(2^31 + 2^32/10^3)
2147913145U, // ceil(2^31 + 2^32/10^4)
2147526598U, // ceil(2^31 + 2^32/10^5)
2147487943U, // ceil(2^31 + 2^32/10^6)
2147484078U, // ceil(2^31 + 2^32/10^7)
2147483691U // ceil(2^31 + 2^32/10^8)
};
return thresholds[index];
// It is equal to ceil(2^31 + 2^32/10^(k + 1)).
// These are stored in a string literal because we cannot have static arrays
// in constexpr functions and non-static ones are poorly optimized.
return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7"
U"\x800001ae\x8000002b"[index];
}

template <typename Float>
Expand Down

2 comments on commit 06b2038

@SanderBouwhuis
Copy link

@SanderBouwhuis SanderBouwhuis commented on 06b2038 Oct 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vitaut
Now we have a bunch of difficult to understand 'magic' numbers.
Something like this is much clearer:

return U"\x9999999a" // ceil(2^31 + 2^32/10^1) = 2'576'980'378
       U"\x828f5c29" // ceil(2^31 + 2^32/10^2) = 2'190'433'321
       U"\x80418938" // ceil(2^31 + 2^32/10^3) = 2'151'778'616
       U"\x80068db9" // ceil(2^31 + 2^32/10^4) = 2'147'913'145
       U"\x8000a7c6" // ceil(2^31 + 2^32/10^5) = 2'147'526'598
       U"\x800010c7" // ceil(2^31 + 2^32/10^6) = 2'147'487'943
       U"\x800001ae" // ceil(2^31 + 2^32/10^7) = 2'147'484'078
       U"\x8000002b" // ceil(2^31 + 2^32/10^8) = 2'147'483'691
       [index];

@vitaut
Copy link
Contributor Author

@vitaut vitaut commented on 06b2038 Oct 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is already clarified in a comment, we don't need to copy paste it.

Please sign in to comment.