11 月 29 日 回复了 daodan1987 创建的主题 › Go 编程语言 › 分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容 |
@lesismal
大致 AI 测了一便,AI 的测试代码,供参考
// Command iochain compares goroutine pools on workloads the earlier synthetic
// benchmarks could not represent:
//
// - real TCP loopback IO instead of time.Sleep, so every task costs syscalls
// and bytes copied, and the pool's own CPU competes with the work;
// - process CPU time per task, reported from runtime/metrics, so "the pool is
// cheap" is measured instead of assumed;
// - a rate-limited upstream, which is how a real chain looks: the producer is
// throttled and the question is whether the pool keeps the pipeline stable
// rather than how deep it can let a backlog grow.
//
// Every pool runs the same client code, the same echo server and the same task
// closure; only the pool differs.
package main
import (
"flag"
"fmt"
"io"
"net"
"os"
"runtime"
"runtime/metrics"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/alitto/pond/v2"
"github.com/panjf2000/ants/v2"
agilepool "github.com/Yiming1997/agilePool/v2"
fibpool "github.com/lesismal/fib/taskpool"
)
type pool interface {
submit(func()) bool
close()
}
type nonePool struct{}
func (nonePool) submit(fn func()) bool { go fn(); return true }
func (nonePool) close() {}
type agilePool struct{ p *agilepool.Pool }
func (a agilePool) submit(fn func()) bool {
a.p.Submit(agilepool.TaskFunc(func() error { fn(); return nil }))
return true
}
func (a agilePool) close() { a.p.Close(); a.p.Wait() }
type antsPool struct{ p *ants.Pool }
func (a antsPool) submit(fn func()) bool { return a.p.Submit(fn) == nil }
func (a antsPool) close() { a.p.Release() }
type pondPool struct{ p pond.Pool }
func (p pondPool) submit(fn func()) bool { return p.p.Go(fn) == nil }
func (p pondPool) close() { p.p.StopAndWait() }
type fibPool struct{ p *fibpool.TaskPool }
func (f fibPool) submit(fn func()) bool { f.p.Go(fn); return true }
func (f fibPool) close() { f.p.Stop() }
func newPool(lib string, size int, queue int) pool {
switch lib {
case "none":
return nonePool{}
case "agile":
return agilePool{agilepool.NewPool(agilepool.NewConfig(
agilepool.WithWorkerNumCapacity(int64(size)),
agilepool.WithTaskQueueSize(int64(queue)),
agilepool.WithCleanPeriod(500 * time.Millisecond),
))}
case "ants":
p, err := ants.NewPool(size)
if err != nil {
panic(err)
}
return antsPool{p}
case "pond":
return pondPool{pond.NewPool(size)}
case "fib":
return fibPool{fibpool.NewWithMode("iochain", fibpool.ModeAdaptive, size, queue)}
}
panic("unknown lib " + lib)
}
// cpuSeconds returns the process CPU time. /cpu/classes/total includes idle
// capacity (it is roughly GOMAXPROCS x wall), so subtract it.
func cpuSeconds() float64 {
s := []metrics.Sample{
{Name: "/cpu/classes/total:cpu-seconds"},
{Name: "/cpu/classes/idle:cpu-seconds"},
}
metrics.Read(s)
if s[0].Value.Kind() == metrics.KindFloat64 && s[1].Value.Kind() == metrics.KindFloat64 {
return s[0].Value.Float64() - s[1].Value.Float64()
}
return 0
}
type hist struct {
mu sync.Mutex
v []float64
}
func (h *hist) observe(x float64) {
h.mu.Lock()
h.v = append(h.v, x)
h.mu.Unlock()
}
func (h *hist) pct(q float64) float64 {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.v) == 0 {
return 0
}
c := append([]float64(nil), h.v...)
sort.Float64s(c)
i := int(q * float64(len(c)-1))
return c[i]
}
// startEchoServer runs a plain goroutine-per-connection echo server. It is the
// same for every pool, so the CPU it consumes is common overhead; it is reported
// separately from the pool's own cost.
func startEchoServer(conns int) (addr string, stop func()) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
var wg sync.WaitGroup
go func() {
for {
c, err := ln.Accept()
if tc, ok := c.(*net.TCPConn); ok {
tc.SetNoDelay(true)
}
if err != nil {
return
}
wg.Add(1)
go func(c net.Conn) {
defer wg.Done()
defer c.Close()
buf := make([]byte, 64)
for {
n, err := c.Read(buf)
if err != nil {
return
}
if _, err := c.Write(buf[:n]); err != nil {
return
}
}
}(c)
}
}()
return ln.Addr().String(), func() { ln.Close(); wg.Wait() }
}
func dialN(addr string, n int) []net.Conn {
conns := make([]net.Conn, 0, n)
for i := 0; i < n; i++ {
c, err := net.Dial("tcp", addr)
if err != nil {
panic(err)
}
if tc, ok := c.(*net.TCPConn); ok {
tc.SetNoDelay(true)
}
conns = append(conns, c)
}
return conns
}
func main() {
scenario := flag.String("scenario", "tcp", "tcp|sleep|fileio|noop")
lib := flag.String("lib", "agile", "agile|ants|pond|fib")
size := flag.Int("size", 256, "worker capacity")
queue := flag.Int("queue", 1024, "handoff/queue size")
tasks := flag.Int("tasks", 200000, "tasks to submit")
producers := flag.Int("producers", 32, "concurrent producers")
taskUs := flag.Int("task-us", 1000, "sleep duration for -scenario sleep")
conns := flag.Int("conns", 256, "TCP connections (one per concurrent task)")
fileMB := flag.Int("file-mb", 8, "fileio: size of the scratch file")
rate := flag.Int("rate", 0, "upstream limit in tasks/s (0 = unthrottled)")
payload := flag.Int("payload", 16, "request/response bytes for tcp")
flag.Parse()
runtime.GOMAXPROCS(runtime.GOMAXPROCS(0))
var (
addr string
stopSrv func()
connCh chan net.Conn
scratch *os.File
)
if scenario == "fileio" {
f, err := os.CreateTemp("", "iochain-.bin")
if err != nil {
panic(err)
}
scratch = f
defer os.Remove(f.Name())
defer f.Close()
if err := f.Truncate(int64(*fileMB) << 20); err != nil {
panic(err)
}
_ = f.Sync()
}
if *scenario == "tcp" {
addr, stopSrv = startEchoServer(*conns)
defer stopSrv()
cs := dialN(addr, *conns)
connCh = make(chan net.Conn, len(cs))
for _, c := range cs {
connCh <- c
}
}
p := newPool(*lib, *size, *queue)
defer p.close()
var off atomic.Int64
bufPool := sync.Pool{New: func() any { b := make([]byte, 128); return &b }}
work := func() {
switch *scenario {
case "tcp":
c := <-connCh
buf := make([]byte, *payload)
c.Write(buf)
io.ReadFull(c, buf)
connCh <- c
case "sleep":
time.Sleep(time.Duration(taskUs) * time.Microsecond)
case "fileio":
// A real pread syscall plus a copy out of the page cache: the cost
// the pool has to compete with, without a server goroutine sharing
// the process.
bp := bufPool.Get().([]byte)
if _, err := scratch.ReadAt(*bp, off.Add(64)%int64(*fileMB<<20)); err != nil {
panic(err)
}
bufPool.Put(bp)
}
}
var submitted, completed, rejected int64
var inFlight, peakInFlight int64
cpu0 := cpuSeconds()
start := time.Now()
var wg sync.WaitGroup
if *rate > 0 {
// Rate-limited upstream: the producer is throttled and never runs ahead.
interval := time.Second / time.Duration(*rate)
deadline := start.Add(time.Duration(int64(*tasks)/int64(*rate)+1) * time.Second)
tk := time.NewTicker(interval)
defer tk.Stop()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < *tasks; i++ {
<-tk.C
if time.Now().After(deadline) {
return
}
atomic.AddInt64(&submitted, 1)
cur := atomic.AddInt64(&inFlight, 1)
for {
peak := atomic.LoadInt64(&peakInFlight)
if cur <= peak || atomic.CompareAndSwapInt64(&peakInFlight, peak, cur) {
break
}
}
ok := p.submit(func() {
work()
atomic.AddInt64(&inFlight, -1)
atomic.AddInt64(&completed, 1)
})
if !ok {
atomic.AddInt64(&inFlight, -1)
atomic.AddInt64(&rejected, 1)
}
}
}()
} else {
per := *tasks / *producers
for k := 0; k < *producers; k++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < per; i++ {
atomic.AddInt64(&submitted, 1)
cur := atomic.AddInt64(&inFlight, 1)
for {
peak := atomic.LoadInt64(&peakInFlight)
if cur <= peak || atomic.CompareAndSwapInt64(&peakInFlight, peak, cur) {
break
}
}
ok := p.submit(func() {
work()
atomic.AddInt64(&inFlight, -1)
atomic.AddInt64(&completed, 1)
})
if !ok {
atomic.AddInt64(&inFlight, -1)
atomic.AddInt64(&rejected, 1)
}
}
}()
}
}
wg.Wait()
for atomic.LoadInt64(&inFlight) > 0 {
time.Sleep(time.Millisecond)
}
elapsed := time.Since(start)
cpu := cpuSeconds() - cpu0
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
fmt.Printf("%s/%s size=%d queue=%d conns=%d tasks=%d rate=%d\n",
*scenario, *lib, *size, *queue, *conns, *tasks, rate)
done := atomic.LoadInt64(&completed)
fmt.Printf(" wall=%8.0fms completed=%d throughput=%9.0f tasks/s per-task=%8.2fus\n",
float64(elapsed.Microseconds())/1000, done, float64(done)/elapsed.Seconds(),
float64(elapsed.Microseconds())/float64(done))
fmt.Printf(" cpu=%6.2fs cpu/task=%7.0fns (%.1f%% of one core at this rate)\n",
cpu, cpu1e9/float64(atomic.LoadInt64(&completed)), cpu/elapsed.Seconds()*100)
fmt.Printf(" peakInFlight=%d rejected=%d\n", atomic.LoadInt64(&peakInFlight), atomic.LoadInt64(&rejected))
fmt.Printf(" heap peak~%dMB end=%dMB gc=%d\n", ms.HeapSys/(1<<20), ms.HeapAlloc/(1<<20), ms.NumGC)
if *scenario == "tcp" {
fmt.Fprintf(os.Stderr, "echo server on %s\n", addr)
}
}
11 月 29 日 回复了 daodan1987 创建的主题 › Go 编程语言 › 分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容 |
@lesismal 可以测测 v2.1.4 默认模式已经改成背压
11 月 28 日 回复了 daodan1987 创建的主题 › Go 编程语言 › 分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容 |
@lesismal 看了下报告又自测了一下,AI 给出的大致结论
「在 5–20 ms 的 IO 密集场景、负载波动的服务里,agilePool 比固定容量池吞吐高 30–45%,且内存只随 worker 数增长(积压百万级任务也不膨胀)。代价是单任务开销更高、空闲时延迟更大——它适合"要弹性"而不是"要极限单点性能"的场景。」
11 月 28 日 回复了 daodan1987 创建的主题 › Go 编程语言 › 分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容 |
@lesismal 十分感谢关注项目!我去看看对比报告。
11 月 27 日 回复了 daodan1987 创建的主题 › Go 编程语言 › 分享一个 Go 池:把“在飞并发”暴露给 KEDA,做 IO 型扩缩容 |
欢迎各位大佬拍砖