基准说明 / 测量源码
定向 NoSplit 热循环源码
这里逐字展示测量所用的源码,保留原有注释、缩进和换行。
main.go
package main
import (
"flag"
"fmt"
"math"
"runtime"
"runtime/metrics"
"sync"
"time"
"upm2/hot"
)
func snapshot() []*metrics.Float64Histogram {
samples := []metrics.Sample{{Name: "/sched/pauses/stopping/gc:seconds"}, {Name: "/sched/pauses/total/gc:seconds"}}
metrics.Read(samples)
return []*metrics.Float64Histogram{samples[0].Value.Float64Histogram(), samples[1].Value.Float64Histogram()}
}
func main() {
duration := flag.Duration("d", 2*time.Second, "sample duration")
flag.Parse()
runtime.GC()
before := snapshot()
end := time.Now().Add(*duration)
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(2)
go func() {
defer wg.Done()
var sum int64
for time.Now().Before(end) {
value, frame := hot.CallNoSplit(100000)
sum += int64(value) + frame.Buf[0]
}
runtime.KeepAlive(sum)
}()
go func() {
defer wg.Done()
var ring [256][]byte
for time.Now().Before(end) {
for j := range ring {
ring[j] = make([]byte, 512)
}
}
runtime.KeepAlive(ring)
}()
}
wg.Wait()
after := snapshot()
for i, name := range []string{"stopping", "total"} {
h := after[i]
var count uint64
for j, n := range h.Counts {
count += n - before[i].Counts[j]
}
fmt.Printf("%s-count %d\n", name, count)
for _, p := range []int{50, 99, 100} {
var cumulative uint64
for j, n := range h.Counts {
cumulative += n - before[i].Counts[j]
if count > 0 && cumulative*100 >= uint64(p)*count {
upper := h.Buckets[j+1]
if math.IsInf(upper, 1) {
panic("unbounded pause bucket")
}
fmt.Printf("bs2-%s-p%d-upper-us %.3f\n", name, p, upper*1e6)
break
}
}
}
}
}
hot/loop.go
package hot
import "upm2/nosplit"
// Frame is a pure stack-resident value (never heap-allocated) sized to keep
// the caller frame above the 128-byte leaf threshold (StackSmall).
type Frame struct {
Buf [16]int64
}
// CallNoSplit crosses a module boundary; only ThinLTO can import NoSplitHot.
func CallNoSplit(n int) (int, Frame) {
var f Frame
t := 0
for i := 0; i < n; i++ {
t += nosplit.NoSplitHot(i)
f.Buf[i&15] = int64(t)
if t > 1<<30 {
t -= 1 << 30
}
}
return t, f
}
nosplit/helper.go
package nosplit
// NoSplitHot is nosplit but too costly for the Go frontend inliner, so its
// body reaches LLVM as a separate symbol and can only be cross-module
// imported by ThinLTO.
//
//go:nosplit
func NoSplitHot(x int) int {
s := x
t := x * 7
for i := 0; i < 32; i++ {
switch i & 3 {
case 0:
s += t*i + 1
case 1:
s -= t ^ (i + 2)
case 2:
s += (i << 2) - t
default:
s ^= t + i*3
}
if s < 0 {
s = -s
}
t = t*31 + 13
}
return s + t
}
go.mod
module upm2
go 1.22