diff options
| author | Axel Wagner <axel.wagner.hh@googlemail.com> | 2025-11-19 09:28:16 +0100 |
|---|---|---|
| committer | Sean Liao <sean@liao.dev> | 2025-11-23 03:49:34 -0800 |
| commit | a18294bb6aa8f0dd656f2bcb6742f9de2936d0dc (patch) | |
| tree | 7d9c0dfc5cfbfe4968c6edfaf6b955e06cbb12e9 /src/sort | |
| parent | 437323ef7b933255c5c7fbb0775019e95f19b05e (diff) | |
| download | go-a18294bb6aa8f0dd656f2bcb6742f9de2936d0dc.tar.xz | |
cmd/internal/obj/arm64, image/gif, runtime, sort: use math/bits to calculate log2
In several places the integer log2 is calculated using loops or similar
mechanisms. math/bits.Len* provide a simpler and more efficient
mechanisms for this.
Annoyingly, every usage has slightly different ideas of what "log2"
means and how non-positive inputs should be handled. I verified the
replacements in each case by comparing the result for inputs from 0
to 1<<16.
Change-Id: Ie962a74674802da363e0038d34c06979ccb41cf3
Reviewed-on: https://go-review.googlesource.com/c/go/+/721880
Reviewed-by: Mark Freeman <markfreeman@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
Diffstat (limited to 'src/sort')
| -rw-r--r-- | src/sort/search_test.go | 10 |
1 files changed, 4 insertions, 6 deletions
diff --git a/src/sort/search_test.go b/src/sort/search_test.go index 49813eaecb..b6ab900abe 100644 --- a/src/sort/search_test.go +++ b/src/sort/search_test.go @@ -5,6 +5,7 @@ package sort_test import ( + "math/bits" "runtime" . "sort" stringspkg "strings" @@ -135,13 +136,10 @@ func TestFind(t *testing.T) { // log2 computes the binary logarithm of x, rounded up to the next integer. // (log2(0) == 0, log2(1) == 0, log2(2) == 1, log2(3) == 2, etc.) func log2(x int) int { - n := 0 - for p := 1; p < x; p += p { - // p == 2**n - n++ + if x < 1 { + return 0 } - // p/2 < x <= p == 2**n - return n + return bits.Len(uint(x - 1)) } func TestSearchEfficiency(t *testing.T) { |
