Go性能调优
// runtime_pprof/main.go
package main
import (
"flag"
"fmt"
"os"
"runtime/pprof"
"time"
)
// 一段有问题的代码
func logicCode() {
var c chan int
for {
select {
case v := <-c:
fmt.Printf("recv from chan, value:%v\n", v)
default:
}
}
}
func main() {
var isCPUPprof bool
var isMemPprof bool
flag.BoolVar(&isCPUPprof, "cpu", false, "turn cpu pprof on")
flag.BoolVar(&isMemPprof, "mem", false, "turn mem pprof on")
flag.Parse()
if isCPUPprof {
file, err := os.Create("./cpu.pprof")
if err != nil {
fmt.Printf("create cpu pprof failed, err:%v\n", err)
return
}
pprof.StartCPUProfile(file)
defer pprof.StopCPUProfile()
}
for i := 0; i < 6; i++ {
go logicCode()
}
time.Sleep(20 * time.Second)
if isMemPprof {
file, err := os.Create("./mem.pprof")
if err != nil {
fmt.Printf("create mem pprof failed, err:%v\n", err)
return
}
pprof.WriteHeapProfile(file)
file.Close()
}
}
上课笔记
go run main.go -cpu=true
先让cpu调试,并在当前目录下生成cpu.pprof
go tool pprof cpu.pprof
然后利用工具 进入交互式状态
Type: cpu
Time: Mar 2, 2021 at 7:41pm (CST)
Duration: 20.15s, Total samples = 56.16s (278.69%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof)
- 输入
top4
返回
top4
Showing nodes accounting for 56.05s, 99.80% of 56.16s total
Dropped 19 nodes (cum <= 0.28s)
flat flat% sum% cum cum%
23.30s 41.49% 41.49% 43.52s 77.49% runtime.selectnbrecv
17.94s 31.94% 73.43% 18.58s 33.08% runtime.chanrecv
12.53s 22.31% 95.74% 56.10s 99.89% main.logicCode
2.28s 4.06% 99.80% 2.29s 4.08% runtime.newstack
(pprof)
- 输入
list logicCode
则返回
list logicCode
Total: 56.16s
ROUTINE ======================== main.logicCode in /Users/zhao/GolangProjects/Test/src/day_03_02/Runtime_pprof/main.go
12.53s 56.10s (flat, cum) 99.89% of Total
. . 8: "runtime/pprof"
. . 9: "time"
. . 10:)
. . 11:
. . 12:// 一段有问题的代码
. 10ms 13:func logicCode() {
. . 14: var c chan int
. . 15: for {
. . 16: select {
12.53s 56.09s 17: case v := <-c:
. . 18: fmt.Printf("recv from chan, value:%v\n", v)
. . 19: default:
. . 20:
. . 21: }
. . 22: }
(pprof)
```