course/pprof/pprof.go

63 lines
1.3 KiB
Go
Raw Normal View History

// runtime_pprof/os.args.go
package main
import (
"flag"
"fmt"
"os"
"runtime/pprof"
"time"
)
// 一段有问题的代码
func logicCode() {
var c chan int //nil 未初始化
for {
select {
case v := <-c: //阻塞
fmt.Printf("recv from chan, value:%v\n", v)
default:
2024-07-16 00:42:15 +08:00
//time.Sleep(time.Millisecond * 500) //优化
}
}
}
func main() {
2024-07-16 00:42:15 +08:00
var isCPUPprof bool //是否开启内存profile的标志位
var isMemPprof bool //是否开启内存profile的标志位
flag.BoolVar(&isCPUPprof, "cpu", false, "turn cpu pprof on")
flag.BoolVar(&isMemPprof, "mem", false, "turn mem pprof on")
flag.Parse()
if isCPUPprof {
2024-07-16 00:42:15 +08:00
f1, err := os.Create("./cpu.pprof") //在当前目录创建cpu.pprof文件
if err != nil {
fmt.Printf("create cpu pprof failed, err:%v\n", err)
return
}
2024-07-16 00:42:15 +08:00
pprof.StartCPUProfile(f1) //往文件中记录cpu的信息
defer func() {
pprof.StopCPUProfile()
f1.Close()
}() //main函数退出之后结束
}
for i := 0; i < 8; i++ {
go logicCode()
}
time.Sleep(20 * time.Second)
if isMemPprof {
2024-07-16 00:42:15 +08:00
f2, err := os.Create("./mem.pprof")
if err != nil {
fmt.Printf("create mem pprof failed, err:%v\n", err)
return
}
2024-07-16 00:42:15 +08:00
pprof.WriteHeapProfile(f2)
f2.Close()
}
}
2024-07-16 00:42:15 +08:00
//生成文件之后用 go tool pprof cpu.pprof
//list logicCode 查看哪一行执行时间长