From 16a7bf420c5c246df2cf27cb31081aafa2483cbf Mon Sep 17 00:00:00 2001 From: Benjamin Nauck Date: Tue, 8 Apr 2025 23:10:10 +0200 Subject: [PATCH] Base: Make sgn branchless --- src/Base/Tools.h | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Base/Tools.h b/src/Base/Tools.h index fba72f2890..895f7922dc 100644 --- a/src/Base/Tools.h +++ b/src/Base/Tools.h @@ -119,14 +119,16 @@ inline T clamp(T num, T lower, T upper) return std::clamp(num, lower, upper); } -template -inline T sgn(T t) +/// Returns -1, 0 or 1 depending on if the value is negative, zero or positive +/// As this function might be used in hot paths, it uses branchless implementation +template +constexpr std::enable_if_t && std::is_signed_v, T> sgn(T val) { - if (t == 0) { - return T(0); - } + int oneIfPositive = int(0 < val); + int oneIfNegative = int(val < 0); + return T(oneIfPositive - oneIfNegative); // 0/1 - 0/1 = -1/0/1 +} - return (t > 0) ? T(1) : T(-1); } template