️ 优化 abs

This commit is contained in:
fumiama 2022-01-08 13:56:19 +08:00
parent f90f20d3a8
commit 8ebe9548f7

View File

@ -17,18 +17,31 @@ func Min(a, b int) int {
return a return a
} }
// intSize is either 32 or 64.
const intSize = 32 << (^uint(0) >> 63)
// Abs 返回绝对值,该函数将被内联 // Abs 返回绝对值,该函数将被内联
func Abs(x int) int { func Abs(x int) int {
if x < 0 { // m := -1 if x < 0. m := 0 otherwise.
return -x m := x >> (intSize - 1)
}
return x // In two's complement representation, the negative number
// of any number (except the smallest one) can be computed
// by flipping all the bits and add 1. This is faster than
// code with a branch.
// See Hacker's Delight, section 2-4.
return (x ^ m) - m
} }
// Abs64 返回绝对值,该函数将被内联 // Abs64 返回绝对值,该函数将被内联
func Abs64(x int64) int64 { func Abs64(x int64) int64 {
if x < 0 { // m := -1 if x < 0. m := 0 otherwise.
return -x m := x >> (64 - 1)
}
return x // In two's complement representation, the negative number
// of any number (except the smallest one) can be computed
// by flipping all the bits and add 1. This is faster than
// code with a branch.
// See Hacker's Delight, section 2-4.
return (x ^ m) - m
} }