2024-07-15 21:36:11 +08:00
|
|
|
// 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) //优化
|
2024-07-15 21:36:11 +08:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2024-07-16 00:42:15 +08:00
|
|
|
var isCPUPprof bool //是否开启内存profile的标志位
|
|
|
|
var isMemPprof bool //是否开启内存profile的标志位
|
2024-07-15 21:36:11 +08:00
|
|
|
|
|
|
|
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文件
|
2024-07-15 21:36:11 +08:00
|
|
|
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函数退出之后结束
|
2024-07-15 21:36:11 +08:00
|
|
|
}
|
|
|
|
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")
|
2024-07-15 21:36:11 +08:00
|
|
|
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-15 21:36:11 +08:00
|
|
|
}
|
|
|
|
}
|
2024-07-16 00:42:15 +08:00
|
|
|
|
|
|
|
//生成文件之后用 go tool pprof cpu.pprof
|
|
|
|
//list logicCode 查看哪一行执行时间长
|