欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

golang 生成并分析 cpu prof 文件

最编程 2024-10-16 12:18:44
...

1. 定义一个接口,请求接口时,生成cpu.prof文件

在主协程中新启一个协程,当请求接口时,生成一个60秒的cpu.prof文件

go func() {
		http.HandleFunc("/prof", startProfileHandler)
		http.ListenAndServe(":9092", nil)
	}()

// startProfileHandler 启动 CPU profiling
func startProfileHandler(w http.ResponseWriter, r *http.Request) {
	// 创建 profile 文件
	f, err := os.Create("cpu.prof")
	if err != nil {
		return
	}
	defer f.Close()

	// 启动 CPU profiling
	if err := pprof.StartCPUProfile(f); err != nil {
		return
	}
	defer pprof.StopCPUProfile() // 在请求结束时停止 CPU profiling

	time.Sleep(60 * time.Second)

	w.Write([]byte("CPU profiling completed, profile saved as cpu.prof"))
}

2. 分析cpu.prof

 go tool pprof -http=:8080 cpu.prof 

点击view, Flat%为占用cpu的百分比,从这里可以看出占用cpu最多的方法

推荐阅读