内存分配
go
// 代码打印实时内存分配
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
fmt.Printf("GC Stats:\n")
fmt.Printf(" NumGC: %d\n", stats.NumGC)
fmt.Printf(" PauseTotal: %v\n", time.Duration(stats.PauseTotalNs))
fmt.Printf(" HeapAlloc: %d KB\n", stats.HeapAlloc/1024)
fmt.Printf(" HeapInuse: %d KB\n", stats.HeapInuse/1024)
fmt.Printf(" StackInuse: %d KB\n", stats.StackInuse/1024)
// 使用 pprof 实时分析内存占用
import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 应用代码
}
// 访问 http://localhost:6060/debug/pprof/heap
// 或使用命令行
// go tool pprof http://localhost:6060/debug/pprof/heap
// 命令行中输入:
/**
(pprof) top10 # 显示前10个内存使用大户
(pprof) list funcName # 显示函数的详细内存分配
(pprof) web # 生成可视化图表
*/
// CPU 性能分析
/**
# 获取30秒的CPU采样
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
# 分析CPU热点
(pprof) top10 # CPU使用率最高的函数
(pprof) peek funcName # 查看函数调用关系
*/
/**
访问 http://localhost:6060/debug/pprof/block 查看同步阻塞分析(如 Mutex)
http://localhost:6060/debug/pprof/goroutine 查看 Goroutine
可以创建如 heap.prof ,并通过pprof.WriteHeapProfile这种写入文件,后续通过 go tool pprof heap.prof 进行查看
*/
//trace 跟踪
func main() {
// 创建trace文件
f, err := os.Create("trace.out")
if err != nil {
panic(err)
}
defer f.Close()
// 开始跟踪
err = trace.Start(f)
if err != nil {
panic(err)
}
defer trace.Stop()
// 被跟踪的代码
tracedWork()
}
//生成 trace 后通过 go tool trace trace.out 进行查看
// 示例:如何在CI中运行性能测试
func ExampleBenchmarkInCI() {
/*
在CI/CD中运行基准测试的脚本示例:
#!/bin/bash
# 运行基准测试并保存结果
go test -bench=. -benchmem -count=5 > new_benchmark.txt
# 与之前的结果比较(需要benchcmp工具)
benchcmp old_benchmark.txt new_benchmark.txt
# 或者使用更现代的工具
benchstat old_benchmark.txt new_benchmark.txt
# 检查性能回归(超过10%的性能下降)
if benchstat -delta-test=ttest old_benchmark.txt new_benchmark.txt | grep -E "\+[0-9]{2}\.[0-9]+%"; then
echo "Performance regression detected!"
exit 1
fi
*/
}