在 Ubuntu 上优化 Golang(Go)程序性能,通常可以从系统层面、Go 本身、代码层面、工具链几个维度来做。下面给你一个比较系统、实用的优化清单。
go version
建议:
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.linux-amd64.tar.gz
ulimit -n
如果太小(如 1024),可修改:
sudo vim /etc/security/limits.conf
* soft nofile 100000
* hard nofile 100000
sudo apt install linux-tools-common
sudo cpupower frequency-set -g performance
sudo swapoff -a
go build -ldflags="-s -w"
-s 去掉符号表-w 去掉 DWARF 调试信息export GOMAXPROCS=$(nproc)
GODEBUG=gctrace=1 ./app
// 不好
for i := 0; i < n; i++ {
s := make([]int, 0)
}
// 好
s := make([]int, 0, n)
sync.Poolvar bufPool = sync.Pool{
New: func() interface{} { return new(bytes.Buffer) },
}
// 慢
func f(v interface{})
// 快
func f(v int)
sem := make(chan struct{}, 10)
避免:
string(b) // 多次转换
尽量复用。
GOGC=200 ./app
默认 100,越大 GC 越少但内存占用高。
import _ "net/http/pprof"
go tool pprof http://localhost:6060/debug/pprof/profile
import "runtime/trace"
go tool trace trace.out
go test -bench=. -benchmem
top / htop
perf top
strace -p pid
| 瓶颈 | 优化方向 |
|---|---|
| CPU | 算法、并发 |
| 内存 | 复用、减少分配 |
| GC | 减少对象 |
| IO | 批量、缓存 |
| 锁 | 减小粒度 |
你可以告诉我:
我可以直接帮你定位具体瓶颈并给代码级优化方案。