MST

星途 面试题库

面试题:Go函数性能监控之基础手段

在Go语言中,简述使用`pprof`进行函数性能监控的基本步骤。
39.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
  1. 引入相关包: 在代码中引入net/httpruntime/pprof包。例如:
import (
    "net/http"
    _ "net/http/pprof"
)
  1. 启动HTTP服务: 在main函数中启动一个HTTP服务来暴露pprof数据。
func main() {
    go func() {
        http.ListenAndServe(":6060", nil)
    }()
    // 主程序逻辑
}
  1. 获取性能数据: 通过浏览器或工具访问http://localhost:6060/debug/pprof/,该页面会展示各种性能分析数据的链接,如:
  • CPU分析:访问http://localhost:6060/debug/pprof/profile,可获取CPU性能分析数据,一般通过go tool pprof工具来分析,例如go tool pprof http://localhost:6060/debug/pprof/profile
  • 内存分析:访问http://localhost:6060/debug/pprof/heap,同样使用go tool pprof分析,如go tool pprof http://localhost:6060/debug/pprof/heap
  • 其他分析:还有goroutine分析(http://localhost:6060/debug/pprof/goroutine)、block分析(http://localhost:6060/debug/pprof/block)等,也用go tool pprof进行深入分析。