对于在Ubuntu/Red Hat系统上分析Go函数的CPU和内存使用情况,可以使用以下工具:
1. 内置pprof工具
Go标准库内置了pprof,可以直接在代码中集成:
import (
"net/http"
_ "net/http/pprof"
"runtime/pprof"
"os"
"time"
)
func main() {
// 启动pprof HTTP服务器
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
// 你的应用程序逻辑
runYourApp()
}
// 特定函数分析示例
func analyzeFunction() {
// CPU分析
f, _ := os.Create("cpu_profile.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
// 要分析的函数
targetFunction()
// 内存分析
memFile, _ := os.Create("mem_profile.prof")
defer memFile.Close()
pprof.WriteHeapProfile(memFile)
}
func targetFunction() {
// 你的目标函数代码
for i := 0; i < 1000000; i++ {
_ = make([]byte, 1024)
time.Sleep(time.Microsecond)
}
}
2. 使用go tool pprof分析
启动应用程序后,通过以下命令收集和分析数据:
# 收集CPU分析数据
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
# 收集内存分析数据
go tool pprof http://localhost:6060/debug/pprof/heap
# 查看函数级别的CPU使用
(pprof) top 10
(pprof) list targetFunction
# 生成火焰图
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile
3. 使用runtime包获取实时指标
import (
"fmt"
"runtime"
"time"
)
func monitorFunction() {
var startMem runtime.MemStats
var endMem runtime.MemStats
runtime.ReadMemStats(&startMem)
startTime := time.Now()
// 执行目标函数
targetFunction()
runtime.ReadMemStats(&endMem)
elapsed := time.Since(startTime)
fmt.Printf("执行时间: %v\n", elapsed)
fmt.Printf("内存分配: %v bytes\n",
endMem.TotalAlloc - startMem.TotalAlloc)
fmt.Printf("堆对象: %v\n",
endMem.HeapObjects - startMem.HeapObjects)
}
4. 使用perf工具(Linux系统)
# 安装perf
sudo apt-get install linux-tools-common # Ubuntu
sudo yum install perf # Red Hat
# 记录性能数据
perf record -g ./your-go-program
perf report
# 生成火焰图
perf script | stackcollapse-perf.pl | flamegraph.pl > flamegraph.svg
5. 使用trace工具分析goroutine
import (
"os"
"runtime/trace"
)
func traceFunction() {
f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()
targetFunction()
}
分析trace文件:
go tool trace trace.out
这些工具可以组合使用,pprof适合函数级别的CPU和内存分析,perf提供系统级视角,trace用于分析goroutine调度和阻塞问题。