Skip to content

Commit 69ed321

Browse files
authored
Merge pull request #264 from chfast/lt_opt
Optimize less-than
2 parents ce3f7a1 + f4cff75 commit 69ed321

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

include/intx/intx.hpp

+8-5
Original file line numberDiff line numberDiff line change
@@ -1087,11 +1087,14 @@ inline constexpr bool operator!=(const T& x, const uint<N>& y) noexcept
10871087
#if !defined(_MSC_VER) || _MSC_VER < 1916 // This kills MSVC 2017 compiler.
10881088
inline constexpr bool operator<(const uint256& x, const uint256& y) noexcept
10891089
{
1090-
const auto xhi = uint128{x[2], x[3]};
1091-
const auto xlo = uint128{x[0], x[1]};
1092-
const auto yhi = uint128{y[2], y[3]};
1093-
const auto ylo = uint128{y[0], y[1]};
1094-
return (unsigned(xhi < yhi) | (unsigned(xhi == yhi) & unsigned(xlo < ylo))) != 0;
1090+
auto xp = intx::uint128{x[2], x[3]};
1091+
auto yp = intx::uint128{y[2], y[3]};
1092+
if (xp == yp)
1093+
{
1094+
xp = intx::uint128{x[0], x[1]};
1095+
yp = intx::uint128{y[0], y[1]};
1096+
}
1097+
return xp < yp;
10951098
}
10961099
#endif
10971100

test/benchmarks/benchmarks.cpp

+6
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,11 @@ BENCHMARK_TEMPLATE(shift, uint512, uint64_t, shl_public)->DenseRange(-1, 3);
351351
return x < y;
352352
}
353353

354+
[[gnu::noinline]] static bool lt_sub(const uint256& x, const uint256& y) noexcept
355+
{
356+
return subc(x, y).carry;
357+
}
358+
354359
[[gnu::noinline]] static bool lt_wordcmp(const uint256& x, const uint256& y) noexcept
355360
{
356361
for (size_t i = 3; i >= 1; --i)
@@ -418,6 +423,7 @@ static void compare(benchmark::State& state)
418423
}
419424
}
420425
BENCHMARK_TEMPLATE(compare, lt_public)->DenseRange(64, 256, 64);
426+
BENCHMARK_TEMPLATE(compare, lt_sub)->DenseRange(64, 256, 64);
421427
BENCHMARK_TEMPLATE(compare, lt_wordcmp)->DenseRange(64, 256, 64);
422428
BENCHMARK_TEMPLATE(compare, lt_halves)->DenseRange(64, 256, 64);
423429
#if INTX_HAS_EXTINT

0 commit comments

Comments
 (0)