在 Linux 环境下用 Go(Golang) 提升性能,通常可以从语言层面、系统层面、部署层面三个维度来做。下面按“实用优先级”给你一个相对系统的总结。
Go 的性能瓶颈常在 GC。
make / newsync.Pool 复用对象// 预分配
s := make([]int, 0, 1000)
m := make(map[string]int, 100)
sem := make(chan struct{}, 10)
for i := 0; i < n; i++ {
sem <- struct{}{}
go func() {
defer func() { <-sem }()
// work
}()
}
atomicsync.Map(读多写少)import "sync/atomic"
atomic.AddInt64(&counter, 1)
[]byte 比 string 频繁拼接更快GOGCGOGC=50 ./app
taskset -c 0-7 ./app
ulimit -n 1000000
或修改 /etc/security/limits.conf
sysctl -w net.core.somaxconn=65535
sysctl -w net.ipv4.tcp_tw_reuse=1
go build -ldflags="-s -w"
import _ "net/http/pprof"
go tool pprof http://localhost:6060/debug/pprof/profile
GOMAXPROCS=4 ./app
bufio| 工具 | 用途 |
|---|---|
| pprof | CPU / 内存 |
| trace | 调度分析 |
| perf | 系统级 |
| flamegraph | 火焰图 |
| stress / wrk | 压测 |
如果你愿意,可以告诉我:
我可以给你更针对性的优化方案。