面试题答案
一键面试- 引入pprof包:
在Go语言项目中,
pprof
包是标准库的一部分,因此无需额外安装,直接在代码中导入即可:
import (
"net/http"
_ "net/http/pprof"
)
- 启动pprof服务:
在
main
函数中,启动一个HTTP服务器来提供pprof数据:
func main() {
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
// 你的业务逻辑代码
}
上述代码在后台启动了一个HTTP服务器,监听在localhost:6060
,nil
表示使用默认的mux
多路复用器。
- 生成分析报告:
- CPU分析:
使用
go tool pprof
工具获取CPU分析报告。在终端中运行:
go tool pprof http://localhost:6060/debug/pprof/profile
这会下载一个CPU分析文件,并启动交互式的pprof
shell。在pprof
shell中,你可以使用各种命令,比如top
查看CPU使用量最高的函数,web
生成一个可视化的SVG图(需要安装graphviz
)。
- 内存分析: 获取内存分析报告,在终端中运行:
go tool pprof http://localhost:6060/debug/pprof/heap
同样会启动pprof
shell,用于分析内存使用情况。
- Goroutine分析: 要分析Goroutine的状态和活动,运行:
go tool pprof http://localhost:6060/debug/pprof/goroutine
在pprof
shell中,使用命令来探索Goroutine相关信息,例如top
查看占用资源最多的Goroutine等。
- 使用程序matic方式获取报告(可选): 你也可以在程序中程序化地获取分析数据,例如获取CPU分析数据并写入文件:
package main
import (
"flag"
"log"
"os"
"runtime/pprof"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
defer f.Close()
err = pprof.StartCPUProfile(f)
if err != nil {
log.Fatal(err)
}
defer pprof.StopCPUProfile()
}
// 业务逻辑代码
}
然后运行程序时带上-cpuprofile
参数指定生成的CPU分析文件路径,之后可以使用go tool pprof
来分析这个文件。