63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
// 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:
|
|
//time.Sleep(time.Millisecond * 500) //优化
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
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 {
|
|
f1, err := os.Create("./cpu.pprof") //在当前目录创建cpu.pprof文件
|
|
if err != nil {
|
|
fmt.Printf("create cpu pprof failed, err:%v\n", err)
|
|
return
|
|
}
|
|
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 {
|
|
f2, err := os.Create("./mem.pprof")
|
|
if err != nil {
|
|
fmt.Printf("create mem pprof failed, err:%v\n", err)
|
|
return
|
|
}
|
|
pprof.WriteHeapProfile(f2)
|
|
f2.Close()
|
|
}
|
|
}
|
|
|
|
//生成文件之后用 go tool pprof cpu.pprof
|
|
//list logicCode 查看哪一行执行时间长
|