Go 调试

2020/08/02 Go 知识点

pprof

web

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    _ "net/http/pprof"
    "time"
)

func main() {
    go func() {
        for {
            fmt.Println(1111)
        }
    }()

    fmt.Println("start api server...")
    //go func() {  
	// _ = http.ListenAndServe(":8080", nil)  
	//}()
    panic(http.ListenAndServe(":6060", nil))
}

pprof web界面: http://localhost:6060/debug/pprof/

  • cpu(CPU Profiling): $HOST/debug/pprof/profile,默认进行 30s 的 CPU Profiling,得到一个分析用的 profile 文件
  • block(Block Profiling):$HOST/debug/pprof/block,查看导致阻塞同步的堆栈跟踪
  • goroutine:$HOST/debug/pprof/goroutine,查看当前所有运行的 goroutines 堆栈跟踪
  • heap(Memory Profiling): $HOST/debug/pprof/heap,查看活动对象的内存分配情况
  • mutex(Mutex Profiling):$HOST/debug/pprof/mutex,查看导致互斥锁的竞争持有者的堆栈跟踪
  • threadcreate:$HOST/debug/pprof/threadcreate,查看创建新 OS 线程的堆栈跟踪
  • map
    • runtime.makemap方法做一些初始化操作,我把map的初始容量设为大于8底层才会走该方法,否则会调用runtime.makemap_small方法。
    • runtime.mapassign_faststr方法 map赋值
    • https://jishuin.proginn.com/p/763bfbd33d03

top

  • flat:当前函数占用CPU的耗时
  • flat::当前函数占用CPU的耗时百分比
  • sun%:函数占用CPU的耗时累计百分比
  • cum:当前函数加上调用当前函数的函数占用CPU的总耗时
  • cum%:当前函数加上调用当前函数的函数占用CPU的总耗时百分比
  • 最后一列:函数名称

交互终端

go tool pprof [http://localhost:6060/debug/pprof/profile?seconds=60

使用生成火焰图

查看cpu情况

go tool pprof -http=:8081 -seconds 10  http://localhost:6060/debug/pprof/profile

打开空不要慌,/ui

http://127.0.0.1:8081/ui/flamegraph?si=cpu 查看cpu时长

查看mem情况

go tool pprof -http=:7778 http://localhost:6060/debug/pprof/heap\?seconds\=30
http://www...:9090/debug/pprof/block
http://www...:9090/debug/pprof/goroutine

涉及方法纪要:

  • runtime.mcall 系统调度
    • runtime.goexit0 会重新调用 runtime.schedule 触发新一轮的 Goroutine 调度,Go 语言中的运行时调度循环会从 runtime.schedule 开始,最终又回到 runtime.schedule
    • runtime.systemstack
  • transport.NewServerTransport 使用来自 config 的 conn 和配置选项创建一个 http2 传输
  • mheap.allocSpan 内存分配 https://www.wangt.cc/2021/01/%E8%AF%A6%E8%A7%A3go%E4%B8%AD%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D/

指定k8s pod进行pprof

kubectl exec -it -n recommend-prod sort-canary-84756b6d9c-mzzrx – /bin/sh

进入指定pod 的shell命令行,执行wget 127.0.0.1:16060/management/debug/pprof/profile?seconds=30

可以用cat命令下载

kubectl exec -n recommend-prod sort-canary-96fd94ff-2lmvv -- cat /app/profile >  profile.pprof 

web界面

go tool pprof -http=:8081 -seconds 10  profile.pprof

link: [[2022-06-13-prometheus]] [[2023-01-13-grpc-stress-tests]]

参考

https://pkg.go.dev/net/http/pprof

https://juejin.cn/post/6844903680232144910

https://zhuanlan.zhihu.com/p/71529062

https://eddycjy.com/posts/go/tools/2018-09-15-go-tool-pprof/

Search

    Table of Contents